01
Overview
Decorators wrap functions to add behavior. @decorator above a function. Decorator is a function that takes a function and returns a function. Use functools.wraps to preserve metadata. Class decorators, stacked decorators, parametrized decorators.
bash
import functools
def log(fn):
@functools.wraps(fn)
def wrapper(*a,**kw):
print(f"calling {fn.__name__}")
return fn(*a,**kw)
return wrapper
@log
def greet(name): return f"Hi {name}"02
Best Practices
Use functools.wraps to preserve __name__, __doc__. Decorators apply bottom-up. Use parametrized decorators with triple nesting. Class decorators can modify class behavior. Common: @property, @staticmethod, @dataclass, @lru_cache.)
Ready to try Decorators?
Visit the official site for the latest version and full documentation.
Visit Decorators