Decorators with arguments in Python
A decorator factory: one more layer to take parameters.
import functools
def repeat(times):
def decorator(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
return [fn(*args, **kwargs) for _ in range(times)]
return wrapper
return decorator
@repeat(times=3)
def roll():
return "tumble"
rolls = roll()
How it works
repeat(times)returns the actual decorator.- That decorator wraps the function as usual.
@repeat(times=3)runs the body three times.
Keywords and builtins used here
decoratordefforrangerepeatreturnrollwrapper
The run, in numbers
- Lines
- 18
- Characters to type
- 254
- Tokens
- 74
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 42 seconds.
Step 3 of 5 in Decorators & closures, step 7 of 53 in Pythonic Python.