Advanced·10 min·advanced · functions
Decorators
Decorators
A decorator is just a function that takes a function and returns a (usually wrapped) function.
The anatomy
@timed # syntactic sugar for: fib = timed(fib)
def fib(n): ...
@wraps(fn) from functools preserves the original function's name and docstring on the wrapper.
Common uses
- Logging / timing
- Caching (
@functools.lru_cache) - Authentication checks
- Retry logic
Try it
- Add an
@functools.lru_cache(maxsize=None)above@timedand watchfib(30)get instant. - Write a
@retry(times=3)decorator factory that retries on exceptions.