Decorator factory is a function that returns a decorator. Allows passing arguments to decorators.
1import functools2import time34# Three levels of nesting5def retry(max_attempts=3, delay=1):6 def decorator(func):7 @functools.wraps(func)8 def wrapper(*args, **kwargs):9 for attempt in range(max_attempts):10 try:11 return func(*args, **kwargs)12 except Exception as e:13 if attempt == max_attempts - 1:14 raise15 print(f"Retry {attempt + 1}/{max_attempts}")16 time.sleep(delay)17 return wrapper18 return decorator1920@retry(max_attempts=5, delay=2)21def unstable_function():22 import random23 if random.random() < 0.7:24 raise ConnectionError("Network error")25 return "Success"
Popular examples:
@lru_cache(maxsize=128).@login_required(redirect_url="/login").@validate(schema=MySchema).@timer(unit="ms").