How do you write a decorator that itself accepts arguments, like `@retry(times=3)`?
Answer
A decorator that takes arguments needs one extra layer of nesting: the outermost function accepts the decorator's own arguments and returns the actual decorator function, which accepts the target function and returns the wrapper, which accepts the target function's arguments at call time. So `@retry(times=3)` first calls `retry(times=3)`, which returns the real decorator, and that decorator is then applied to the function immediately below it, exactly like a normal argument-less decorator would be.
Strong answer includes
- needs an extra outer layer that returns the real decorator
- outer layer takes the decorator's own arguments
- the returned decorator is then applied to the function as usual
Practical example
def retry(times):
if times < 1:
raise ValueError("times must be at least 1")
def decorator(func):
def wrapper(*args, **kwargs):
for attempt in range(times):
try:
return func(*args, **kwargs)
except Exception:
if attempt == times - 1:
raise
return wrapper
return decoratordefines a three-level decorator factory.