How do you write a decorator that itself accepts arguments, like @retry(times=3)?
Short answer
Add an EXTRA outer layer: a function that takes the decorator's OWN arguments and returns the actual decorator function (which in turn takes the target function and returns the wrapper) — three levels of nested functions total, letting you configure the decorator's behavior per…
Advertisement
AModel answer
Add an EXTRA outer layer: a function that takes the decorator's OWN arguments and returns the actual decorator function (which in turn takes the target function and returns the wrapper) — three levels of nested functions total, letting you configure the decorator's behavior per use.
def retry(times):
def decorator(func):
@functools.wraps(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 decorator
@retry(times=3)
def flaky_operation():
...Real-world example
Building a configurable retry decorator that lets each usage specify its own number of retry attempts.
Likely follow-ups
- How would you make the 'times' argument to @retry optional, so @retry (without parentheses) also works?
Related topics