Building Python Decorators
Advanced Abstractions
Decorators for Cross-Cutting Concerns
Decorators wrap functions or methods to add behavior (logging, auth, retries) without scattering boilerplate.
Basic decorator
from functools import wraps
def log_calls(func):
@wraps(func)
def wrapper(*args, **kwargs):
logger.info('Calling %s', func.__name__)
return func(*args, **kwargs)
return wrapper
@log_calls
def process(order_id): ...
- Always use
@wrapsto preserve metadata (docstring, name, annotations).
Parameterized decorator
def retry(times=3):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
...
return wrapper
return decorator
- The outer function captures configuration.
Decorating methods & classes
- Methods receive
selfas the first argument; decorators work the same. - Class decorators can inject behavior or registration hooks.