Decorators
A decorator is a function that takes a function and returns a replacement for it. The @name line above a definition applies one, letting you add behaviour such as timing, caching, or access checks without editing the function body.
Detailed Explanation
Say you have forty view functions in a web app and you want every one of them to log how long it took. You could paste a timer at the top and bottom of each body. That is forty copies of the same four lines, and the next change touches forty places. The problem is not the timing code; it is that the timing code and the business logic are tangled together.
Decorators untangle them. Because functions in Python are ordinary objects, you can write a function that accepts a function, builds a new function around it, and returns that. The inner wrapper does the timing and calls the original in the middle. You then rebind the original name to the wrapper, so every caller gets the timed version without knowing it.
That rebinding by hand looks like charge_card = timed(charge_card). It works, and it is precisely what a decorator does. The @timed syntax, added in Python 2.4, only moves that line above the definition so a reader sees the behaviour before they read the body. There is no magic underneath.
Three details make the difference between a decorator that works and one that quietly breaks things.
The wrapper must accept any arguments. Write it as def wrapper(*args, **kwargs) and pass them straight through, otherwise the decorator only fits functions with one specific signature.
The wrapper must copy the original's metadata. A fresh wrapper has __name__ == "wrapper" and no docstring, which breaks help text, documentation generators, and error messages. functools.wraps copies __name__, __doc__, __module__, annotations, and a __wrapped__ back-pointer that lets inspect.signature recover the real signature.
The decorator runs at definition time, not call time. When the module is imported, Python evaluates the decorator once per decorated function. The wrapper it returns is what runs per call.
A decorator that takes arguments needs one more layer. @retry(attempts=3) is not a decorator; it is a call that returns a decorator. So you write a function that takes the options, defines the decorator inside it, and returns that decorator — three nested defs. This is the part that confuses people, and the fix is to read the @ line as "evaluate this expression, then apply the result".
Stacked decorators apply bottom-up. @outer above @inner means outer(inner(func)), so inner is the closest wrapper to your code and outer is the outermost. At call time the order reverses: outer sees the call first. Ordering matters when one decorator authenticates and another caches — caching before authenticating is a security bug.
The cost is one extra Python function call per call, roughly tens of nanoseconds in CPython, plus a stack frame in every traceback. That is irrelevant for a request handler and measurable in a tight numeric loop. The bigger cost is readability: a stack of five decorators hides a lot of control flow.
The standard library ships the decorators you will reach for most: functools.lru_cache and functools.cache for memoising pure functions, functools.cached_property, property, classmethod, staticmethod, dataclasses.dataclass, and contextlib.contextmanager.
Code Examples
import functools
import time
def timed(func):
@functools.wraps(func) # copies __name__, __doc__, __wrapped__ over
def wrapper(*args, **kwargs): # accept ANY signature, pass it straight through
start = time.perf_counter()
try:
return func(*args, **kwargs)
finally: # report even if the wrapped call raises
print(f"{func.__name__} took {time.perf_counter() - start:.6f}s")
return wrapper
@timed
def count_server_errors(lines):
"""Count 5xx responses in a log."""
return sum(1 for line in lines if line.startswith("5"))
print(count_server_errors(["200 /home", "500 /checkout"]))
# count_server_errors took 0.000004s (exact number varies)
# 1
# Thanks to functools.wraps, introspection still sees the real function.
print(count_server_errors.__name__) # count_server_errors
print(count_server_errors.__doc__) # Count 5xx responses in a log.
# The @ syntax is only shorthand for this:
def plain(lines):
return len(lines)
plain = timed(plain) # identical to writing @timed above itimport functools
def retry(attempts, exceptions=(Exception,)):
"""A decorator FACTORY: called with options, returns the real decorator."""
def decorator(func): # this layer receives the function
@functools.wraps(func)
def wrapper(*args, **kwargs): # this layer receives the call
for attempt in range(1, attempts + 1):
try:
return func(*args, **kwargs)
except exceptions:
if attempt == attempts:
raise # out of retries: let it propagate
print(f"attempt {attempt} failed, retrying")
return wrapper
return decorator
call_count = 0
@retry(attempts=3, exceptions=(ConnectionError,)) # note the CALL, then the @
def load_session(user_id):
global call_count
call_count += 1
if call_count < 3:
raise ConnectionError("cache node unreachable")
return {"user_id": user_id}
print(load_session(42))
# attempt 1 failed, retrying
# attempt 2 failed, retrying
# {'user_id': 42}import functools
def tag(label):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"enter {label}")
result = func(*args, **kwargs)
print(f"exit {label}")
return result
return wrapper
return decorator
@tag("outer") # applied LAST, so it is the outermost wrapper
@tag("inner") # applied FIRST, so it sits closest to the body
def charge_card(amount_cents):
print(f"charging {amount_cents}")
return amount_cents
charge_card(1999)
# enter outer <- outermost wrapper runs first
# enter inner
# charging 1999
# exit inner
# exit outer
# lru_cache: a decorator you will use for real. Memoises a pure function.
@functools.lru_cache(maxsize=128)
def shipping_cost(country_code, weight_kg):
print(f"computing for {country_code}") # shows when the body actually runs
return 5.0 + 2.5 * weight_kg
print(shipping_cost("IN", 2)) # computing for IN / 10.0
print(shipping_cost("IN", 2)) # 10.0 <- served from cache, no print
print(shipping_cost.cache_info().hits) # 1Common Gotchas
Forgetting `functools.wraps`
without it the decorated function reports its name as `wrapper`, loses its docstring, and confuses `inspect.signature`, Sphinx, and `pickle`. Debugging a service where every function is called `wrapper` is miserable. Add `@functools.wraps(func)` to every wrapper you write.
Decorators run at import time
the decorator body executes once when the module is imported, not when the function is called. A decorator that opens a database connection or registers a route does that work during import, which makes import order significant and can make `--help` slow.
Stacking order is bottom-up
`@cache` above `@require_login` means results are cached *outside* the auth check, so the first authorised caller's data is served to everyone. The decorator listed last is applied first and sits nearest the function.
`lru_cache` on methods leaks memory
the cache key includes `self`, so every instance you ever passed stays referenced and is never collected. It also raises `TypeError` on unhashable arguments such as lists or dicts. Use `functools.cached_property` for per-instance caching instead.