Decorators in Python can also take arguments. This allows you to customize the behavior of the decorator based on the arguments passed to it.
Here's an example of a decorator that takes arguments:
def repeat(num_repeats): def decorator(func): def wrapper(*args, **kwargs): for i in range(num_repeats): result = func(*args, **kwargs) return result return wrapper return decorator |
In this example, the repeat decorator takes an argument num_repeats and returns a new decorator that takes a function func as its argument. The new decorator returns a new function wrapper that wraps the original function with repeated execution. When the new function is called, it calls the original function with the given arguments multiple times, as specified by num_repeats.
To use this decorator with a function, simply apply it to the function and provide the argument(s):
@repeat(num_repeats=3)def my_function(): print("Function call") |
In this example, the @repeat(num_repeats=3) syntax applies the repeat decorator to the my_function() function with num_repeats=3. When the function is called, the decorator will execute the function three times.
Note that the repeat decorator takes an argument and returns a decorator that takes a function. This is because the arguments to a decorator are evaluated at decoration time, while the function arguments are evaluated at runtime. By returning a decorator that takes a function, we can separate the decoration process from the function execution.
Using a decorator that takes arguments can be useful when you need to add customizable behavior to a function. It allows you to create a single decorator that can be applied to multiple functions with different arguments, making it easier to reuse and maintain.