April 2019
Intermediate to advanced
646 pages
16h 48m
English
In real usage scenarios, there is often a need to use decorators that can be parameterized. When the function is used as a decorator, then the solution is simple – a second level of wrapping has to be used. Here is a simple example of the decorator that repeats the execution of a decorated function the specified number of times every time it is called:
def repeat(number=3):
"""Cause decorated function to be repeated a number of times.
Last value of original function call is returned as a result.
:param number: number of repetitions, 3 if not specified """ def actual_decorator(function): def wrapper(*args, **kwargs): result = None for _ in range(number): result = function(*args, **kwargs) return result return wrapper ...