Here's an example of a run_n_times decorator that can be used to execute a function a specified number of times:
def run_n_times(n): def decorator(func): def wrapper(*args, **kwargs): for i in range(n): func(*args, **kwargs) return wrapper return decorator |
This decorator takes an integer n as an argument and returns a decorator that takes a function as its argument. The returned decorator wraps the original function with a loop that executes it n times. The wrapper function returns None because it doesn't need to return a value.
Here's an example of how to use this decorator to execute a function three times:
@run_n_times(3)def say_hello(name): print(f"Hello, {name}!")say_hello("Alice") |
Output:
Hello, Alice!Hello, Alice!Hello, Alice! |
In this example, the say_hello function is decorated with the run_n_times decorator with n=3. When the function is called with the argument "Alice", the decorator executes it three times, printing "Hello, Alice!" each time.
Note that the run_n_times decorator can be used with any function that takes any number of arguments. It's a simple example of how decorators can be used to add functionality to existing functions without modifying their code.