To write a decorator that takes arguments in Python, you need to add an extra outer layer function. This creates a three-level nested function structure (a decorator factory) where:
The outermost function accepts the custom decorator arguments.
The middle function receives the actual function to be decorated.
The innermost function handles the arguments passed to the decorated function itself.
import time
from functools import wraps
def retry(times=3, delay=1.0):
def deco(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return fn(*args, **kwargs)
except Exception:
if attempt == times:
raise
time.sleep(delay * attempt)
return wrapper
return deco