Lesson 23 of 52Pythonic Python
Decorators
Wrap functions to add timing, retries, caching and routing, and understand what the @ line really does.
@app.get("/users"), @pytest.fixture, @lru_cache, @dataclass, @property: modern Python is full of lines starting with @. Each one is a decorator, a function that takes your function and returns an upgraded version. Once you can write your own, a whole layer of framework "magic" turns into ordinary code you can read, and you can add logging, timing or retries to any function with one line.
Functions are values
Decorators rest on two facts you met in the functions unit: functions are objects you can pass around, and a function can define and return another function, which remembers the variables around it (a closure).
Press Run (⌘ Enter) to see what happens.A decorator is just a function that takes a function and returns a new one that wraps it.
Your first decorator
Press Run (⌘ Enter) to see what happens.@shout above a def means "define the function, then immediately do farewell = shout(farewell)". That is all the @ syntax is. The *args, **kwargs in wrapper let it accept any arguments and pass them through unchanged, so one decorator works on any function.
def creates a function object and binds the name greet.
What does this print?
def log(func):
def wrapper():
print("before")
func()
print("after")
return wrapper
@log
def work():
print("working")
work()log above) run?Keep the identity with functools.wraps
There is a problem with our wrapper: it replaces the original's name and docstring. Debuggers, logs, documentation tools and frameworks all see wrapper instead.
Press Run (⌘ Enter) to see what happens.Always use @functools.wraps(func) on your wrapper. It also sets wrapper.__wrapped__ to the original, which tools use to see through the decorator.
A practical decorator: timing
Press Run (⌘ Enter) to see what happens.The try/finally makes sure the timing prints even if the function raises. time.perf_counter() is the right clock for measuring durations.
Decorators with arguments
@retry(times=3) has parentheses, so retry(times=3) is called first, and whatever it returns is the real decorator. That means three layers: a function that takes the options, returns a decorator, which returns a wrapper.
Press Run (⌘ Enter) to see what happens.For @retry(times=3) above def fetch, put the steps in the order they happen.
- Tap the steps below in the right order.
Real retry code also waits between attempts, often with exponential backoff (1s, 2s, 4s...), and only retries errors that are worth retrying, like timeouts. Libraries such as tenacity do this for you.
A production retry: backoff, jitter and what not to retry
The toy retry above hammers the server again instantly, retries forever-ish on every ConnectionError, and cannot be tested without real failures. Here is the version you would actually defend in code review. It is worth studying because every choice in it is a lesson someone learned in an incident.
Press Run (⌘ Enter) to see what happens.What each decision buys you:
- Exponential backoff with a cap. The ceiling doubles (0.5s, 1s, 2s, 4s) so a struggling server gets breathing room, and
capstops the wait growing without limit. - Jitter. If a thousand clients fail at the same moment and all wait exactly 1s, they all retry at the same moment and knock the server over again. Picking a random delay between 0 and the ceiling ("full jitter") spreads them out. This is the pattern AWS's architecture guidance popularised, and it is what interviewers want to hear when they ask about a "thundering herd".
- An allow-list of retryable errors. A
ValueErrorfrom bad input will fail the same way every time, so retrying only wastes time. Retry timeouts, connection resets and 5xx or 429 responses. Never retry 4xx validation errors. - Re-raise the original on the last attempt. The caller sees the real error and traceback, plus a note saying how hard you tried. Raising a brand new exception would throw that information away.
- Injected
sleepandrng. Tests pass a fakesleepand a seeded random source, so they run instantly and give the same output every time. This is dependency injection, which Testing Code That Touches the Outside World covers in depth. - Keyword-only options (the
*in the signature).@retry(attempts=4)reads clearly;@retry(4, 0.5, 8.0)does not.
One rule matters more than all of these: only retry operations that are safe to repeat. Re-sending a "charge the card" request after a timeout can charge the customer twice, because the timeout may have happened after the server did the work. Payment APIs solve this with an idempotency key the server uses to recognise duplicates. In production, reach for tenacity (or your HTTP client's built-in retry settings) rather than maintaining your own, but you now know exactly what to configure.
Stacking decorators
You can put several decorators on one function. They are applied bottom up at definition time, so the one nearest the def wraps first and the top one ends up outermost. At call time the outermost wrapper runs first, like layers of an onion.
Press Run (⌘ Enter) to see what happens.@outer over @inner over def handler means handler = outer(inner(handler)).
At definition time Python starts at the bottom: def handler creates the original function.
Order changes behaviour, and real bugs come from getting it wrong:
- Routing over auth. In Flask,
@app.route("/admin")must be the top decorator. If you write@login_requiredabove it, the route registers the unprotected inner function, and the login check wraps a copy nobody calls. The page is open to everyone and nothing errors. FastAPI avoids this class of bug by using dependencies instead of auth decorators. - Cache over timing.
@cacheabove@timedmeans cache hits skip the timer entirely, so you only time real work. Swap them and every call is timed, including the instant cache hits, which drags your average down. - Retry over timeout. A per-attempt timeout belongs inside the retry; a total deadline belongs outside it.
What does this print?
def tag(name):
def deco(func):
def wrapper():
return f"<{name}>{func()}</{name}>"
return wrapper
return deco
@tag("b")
@tag("i")
def text():
return "hi"
print(text())Caching with lru_cache and cache
The standard library ships a decorator you will use constantly. functools.lru_cache stores results keyed by the arguments, so repeated calls return instantly. maxsize caps how many results it keeps, evicting the least recently used ones. functools.cache is the same with no limit.
Press Run (⌘ Enter) to see what happens.Arguments must be hashable (they become dict keys), so you cannot cache a function that takes a list. And only cache pure functions: same input, same output, no side effects.
@cache?Decorating methods
A plain function decorator works on methods with no changes. A method is just a function stored on a class, and when you call obj.method(x), Python passes obj as the first positional argument, so it arrives in the wrapper's *args and is passed straight through.
The trouble starts when you combine your decorator with @classmethod, @staticmethod or @property. Those three do not return functions. They return descriptor objects that control how the attribute behaves when looked up on a class or instance (Descriptors and Attribute Lookup explains the machinery). Your wrapper expects to call a function, so it has to sit underneath them, closest to the def.
Press Run (⌘ Enter) to see what happens.The rule: @classmethod, @staticmethod and @property go on top, your decorators go below. (Python 3.9 briefly let @classmethod wrap @property to make class properties. That was deprecated in 3.11 and removed in 3.13, so do not copy old answers that use it.)
Two method-specific traps to know about:
- Caching methods.
@lru_cacheon a method includesselfin the cache key, so the cache holds a reference to every instance it has seen and they are never garbage collected. functools, itertools and operator covers this "method trap" and the fixes (cached_property, or a cache keyed on the values you actually need). - Per-instance state. Anything the decorator stores (a counter, a cache) lives on the wrapper, which is shared by every instance of the class. If you want state per object, store it on
selfinside the wrapper instead.
Class-based and stateful decorators
A decorator only has to be a callable that takes a function. A class is callable, so a class can be a decorator: @CountCalls above def ping means ping = CountCalls(ping), an instance. Give the instance a __call__ method and it behaves like a function, while ordinary attributes hold the state. This reads better than closures once the state grows past one variable, and the state is easy to inspect in tests.
Press Run (⌘ Enter) to see what happens.functools.update_wrapper(self, func) is what @wraps does under the hood, applied to the instance.
The TypeError is the classic class-decorator bug. Functions have a __get__ method, which is how obj.method becomes a bound method with self filled in. A plain instance of your class has no __get__, so Client().fetch returns the CountCalls object itself, self is never passed, and "/users" lands in the self slot. Adding __get__ that returns types.MethodType(self, instance) restores normal method binding.
For simple state, a function attribute is often enough: set wrapper.calls = 0 inside the decorator and increment it in the wrapper. Reach for a class when the decorator has several pieces of state, configuration, or methods of its own, like fib.cache_clear() on an lru_cache function.
Decorators that work with and without parentheses
Libraries like dataclasses let you write both @dataclass and @dataclass(frozen=True). The trick is to check whether the first argument is the function itself:
def retry(func=None, *, attempts=3):
def decorator(f):
... # build and return the wrapper
if func is None: # used as @retry(attempts=5)
return decorator
return decorator(func) # used as bare @retryThe options must be keyword-only, otherwise @retry(5) would pass 5 as func. Use this in a shared library where convenience matters. In application code, always requiring parentheses is simpler and has no surprises.
Class decorators and frameworks
A decorator can also take a class and return it, modified or registered. @dataclass is one: it reads the annotations and adds methods. @functools.total_ordering is another.
Now you can read framework code. FastAPI's @app.get("/users") is a decorator with arguments. It does not even need to wrap your function. It registers it in a routing table and returns it unchanged:
Press Run (⌘ Enter) to see what happens.That is the real shape of FastAPI, Flask and Click routing. You will write @app.get for real in the Python Backend course.
Registries beyond routes
The same shape powers pytest fixtures, Celery tasks, Click commands, Django signal receivers and plugin systems. You will often want one in your own code: a dict from a key to a handler, filled by a decorator, instead of a long if/elif chain that every new format has to edit.
Press Run (⌘ Enter) to see what happens.Three details separate a good registry from a fragile one. It rejects duplicates loudly, because two handlers silently fighting over one key is a nightmare to debug. Its error message lists what is available. And the decorator returns the function unchanged, so to_csv can still be called and unit tested directly.
The catch everyone hits once: registration happens when the module is imported, because that is when the def and the decorator run. If exporters/xlsx.py is never imported, its handler never registers, and you get "unknown format" with no other clue. Frameworks deal with this by importing your modules for you (Django's app loading, pytest's conftest.py discovery) or through package entry points, which Modules and Packages covers. In your own code, import every handler module explicitly in one place, such as the package's __init__.py.
Typing a decorator
Type checkers see straight through the decorated name. If your decorator is annotated as Callable[..., Any] -> Callable[..., Any], every function it touches loses its parameter types and return type, and callers can pass anything. The fix is a ParamSpec, which captures a whole parameter list so the wrapper can promise "same arguments, same return type":
import functools
from collections.abc import Callable
def timed[**P, R](func: Callable[P, R]) -> Callable[P, R]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
return func(*args, **kwargs)
return wrapper
@timed
def charge(user_id: int, cents: int) -> bool: ...
charge("u1", 500) # checker error: "u1" is not an int[**P, R] is the Python 3.12 syntax: **P declares a ParamSpec, R an ordinary type variable. Typing Patterns for Real Code takes this further: decorators that add or remove an argument with Concatenate, decorator factories, and typing class-based decorators.
A @retry decorator
Write a decorator factory retry(times, exceptions=(Exception,)).
- The decorated function is called up to
timesattempts in total. - If an attempt raises one of the exception types in
exceptions, try again. - If every attempt fails, re-raise the last exception (the original error, not a new one).
- Exceptions not listed in
exceptionsmust propagate immediately, without retrying. - Return the function's result as soon as an attempt succeeds.
- Preserve the original function's
__name__and docstring.
@retry(times=3, exceptions=(ConnectionError,))
def fetch():
... # fails twice with ConnectionError, then returns "ok"
fetch() # "ok", after 3 callsCount the calls
Write a decorator count_calls that counts how many times the decorated function has been called. Store the count in an attribute calls on the returned wrapper, starting at 0.
The wrapper must pass any arguments through, return the original result, and keep the original __name__ (use functools.wraps).
@count_calls
def add(a, b):
return a + b
add.calls # 0
add(1, 2) # 3
add(b=5, a=1) # 6
add.calls # 2- decorator
- A callable that takes a function (or class) and returns a replacement.
@dabovedef fmeansf = d(f). - wrapper
- The inner function a decorator returns; it calls the original and adds behaviour around it.
- functools.wraps
- Copies the original function's name, docstring and
__wrapped__onto the wrapper. - decorator factory
- A function like
retry(times)that takes options and returns a decorator. - lru_cache
- Memoises a pure function's results by argument, evicting the least recently used when full.