A decorator takes a function, wraps it with extra behaviour, and returns the new function. The @name line above a function is shorthand for func = name(func).
Example: a decorator that times a function:
import time
from functools import wraps
def timer(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = fn(*args, **kwargs)
print(f"{fn.__name__} took {time.perf_counter() - start:.3f}s")
return result
return wrapper
@timer
def slow():
return sum(range(5_000_000))
Use functools.wraps so the wrapped function keeps its name and docstring.
Typical uses: logging, timing, caching (functools.lru_cache), checking login or permissions (@login_required) and registering routes (@app.route). They keep this cross-cutting code out of your main logic.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
A decorator takes a function, wraps it with extra behaviour, and returns the new function. The
@nameline above a function is shorthand forfunc = name(func).Example: a decorator that times a function:
Use
functools.wrapsso the wrapped function keeps its name and docstring.Typical uses: logging, timing, caching (
functools.lru_cache), checking login or permissions (@login_required) and registering routes (@app.route). They keep this cross-cutting code out of your main logic.