Skip to content

Lesson 23 of 52Pythonic Python

Decorators

Wrap functions to add timing, retries, caching and routing, and understand what the @ line really does.

24 min read0/6 questions

@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).

Python
def make_greeter(greeting): def greet(name): # inner function return f"{greeting}, {name}!" # remembers 'greeting' return greet # return the function itself, not a call hello = make_greeter("Hello")howdy = make_greeter("Howdy")print(hello("Ada"), howdy("Sam"))print(hello.__name__)
Output
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

Python
def shout(func): def wrapper(*args, **kwargs): result = func(*args, **kwargs) # call the original return result.upper() + "!" return wrapper def greet(name): return f"hello {name}" greet = shout(greet) # wrap it by handprint(greet("leo")) @shout # exactly the same thing, with syntaxdef farewell(name): return f"bye {name}" print(farewell("leo"))
Output
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.

What @shout does to the name greet
def greet(name): ...
NamesObjects in memorygreetfunctiongreet (original)

def creates a function object and binds the name greet.

1/3
Predict the outputPython

What does this print?

def log(func):
  def wrapper():
      print("before")
      func()
      print("after")
  return wrapper

@log
def work():
  print("working")

work()
Need a nudge? Hints walk you through it.
Quick check
When does the decorator function itself (log above) run?
Need a nudge? A hint rules out a wrong answer.

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.

Python
import functools def plain(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper def proper(func): @functools.wraps(func) # copy name, docstring, etc. onto wrapper def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper @plaindef add(a, b): """Add two numbers.""" return a + b @properdef sub(a, b): """Subtract b from a.""" return a - b print(add.__name__, add.__doc__)print(sub.__name__, sub.__doc__)
Output
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

Python
import functools, time def timed(func): @functools.wraps(func) def wrapper(*args, **kwargs): start = time.perf_counter() try: return func(*args, **kwargs) finally: ms = (time.perf_counter() - start) * 1000 print(f"{func.__name__} took {ms:.1f} ms") return wrapper @timeddef slow_sum(n): return sum(i * i for i in range(n)) print(slow_sum(200_000))
Output
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.

Python
import functools def retry(times): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): for attempt in range(1, times + 1): try: return func(*args, **kwargs) except ConnectionError as e: print(f" attempt {attempt} failed: {e}") raise ConnectionError(f"gave up after {times} attempts") return wrapper return decorator calls = {"n": 0} @retry(times=3)def flaky_fetch(): calls["n"] += 1 if calls["n"] < 3: raise ConnectionError("timeout") return "data" print(flaky_fetch())
Output
Press Run (⌘ Enter) to see what happens.
Put it in order4 steps

For @retry(times=3) above def fetch, put the steps in the order they happen.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

Python
import functools, random, time class TransientError(Exception): """Worth retrying: timeouts, 503s, dropped connections.""" def retry(*, attempts=4, base=0.5, cap=8.0, retry_on=(TransientError,), sleep=time.sleep, rng=random.random): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): for attempt in range(1, attempts + 1): try: return func(*args, **kwargs) except retry_on as e: if attempt == attempts: e.add_note(f"gave up after {attempts} attempts") raise ceiling = min(cap, base * 2 ** (attempt - 1)) delay = rng() * ceiling # "full jitter" print(f" attempt {attempt} failed ({e}); sleeping {delay:.2f}s") sleep(delay) return wrapper return decorator # Test without waiting: record the sleeps instead of doing them.slept = []rng = random.Random(7).randomresults = iter([TransientError("503"), TransientError("timeout"), "ok"]) @retry(attempts=4, sleep=slept.append, rng=rng)def fetch_invoice(invoice_id): outcome = next(results) if isinstance(outcome, Exception): raise outcome return f"invoice {invoice_id}: {outcome}" print(fetch_invoice(42))print("total sleep:", round(sum(slept), 2)) @retry(attempts=3, sleep=slept.append, rng=rng)def always_down(): raise TransientError("connection reset") try: always_down()except TransientError as e: print("final:", e, e.__notes__) @retry(sleep=slept.append)def bad_input(): raise ValueError("invoice id must be positive") try: bad_input()except ValueError as e: print("not retried:", e)
Output
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 cap stops 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 ValueError from 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 sleep and rng. Tests pass a fake sleep and 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.

Python
import functools def trace(label): def decorator(func): print(f"applying {label}") @functools.wraps(func) def wrapper(*args, **kwargs): print(f"-> enter {label}") result = func(*args, **kwargs) print(f"<- leave {label}") return result return wrapper return decorator @trace("outer")@trace("inner")def handler(): print(" handler runs") return "ok" print("--- calling")print(handler())
Output
Press Run (⌘ Enter) to see what happens.

@outer over @inner over def handler means handler = outer(inner(handler)).

handler = outer(inner(handler))
  1. outer wrapperapplied last, runs first on every call
  2. inner wrapperapplied first, nearest the def
  3. handler (original)your function, at the centre

At definition time Python starts at the bottom: def handler creates the original function.

1/4

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_required above 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. @cache above @timed means 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.
Predict the outputPython

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())
Need a nudge? Hints walk you through it.

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.

Python
from functools import cache, lru_cache @cachedef fib(n): return n if n < 2 else fib(n - 1) + fib(n - 2) print(fib(90)) # instant; without @cache this would take agesprint(fib.cache_info()) @lru_cache(maxsize=2)def square(n): print(f" computing {n}") return n * n square(2); square(2); square(3); square(4); square(2)
Output
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.

Quick check
Which function is safe to decorate with @cache?
Need a nudge? A hint rules out a wrong answer.

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.

Python
import functools def timed(func): @functools.wraps(func) def wrapper(*args, **kwargs): print(f"timing {func.__qualname__}, first arg: {type(args[0]).__name__ if args else None}") return func(*args, **kwargs) return wrapper class Report: def __init__(self, title): self.title = title @timed # works: self arrives in *args def render(self, width): return self.title.center(width, "*") @classmethod @timed # right: classmethod outermost def blank(cls): return cls("untitled") print(Report("Q3").render(10))print(Report.blank().title) class Broken: @timed # wrong: timed receives a classmethod object @classmethod def blank(cls): return cls() try: Broken.blank()except TypeError as e: print("TypeError:", e)
Output
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_cache on a method includes self in 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 self inside the wrapper instead.
Quick check
You want to log every call to a class method. Which stacking is correct?
Need a nudge? A hint rules out a wrong answer.

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.

Python
import functools, types class CountCalls: def __init__(self, func): functools.update_wrapper(self, func) # copy __name__, __doc__, __wrapped__ self.func = func self.calls = 0 def __call__(self, *args, **kwargs): self.calls += 1 return self.func(*args, **kwargs) @CountCallsdef ping(host): return f"pong from {host}" ping("a"); ping("b")print(ping.__name__, ping.calls) class Client: @CountCalls def fetch(self, path): return f"GET {path}" try: Client().fetch("/users")except TypeError as e: print("TypeError:", e) class CountCallsFixed(CountCalls): def __get__(self, instance, owner): if instance is None: return self return types.MethodType(self, instance) # bind like a function would class Client2: @CountCallsFixed def fetch(self, path): return f"GET {path}" c = Client2()print(c.fetch("/users"), c.fetch("/orders"))print(Client2.fetch.calls)
Output
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 @retry

The 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:

Python
class App: def __init__(self): self.routes = {} def get(self, path): def decorator(func): self.routes[("GET", path)] = func # register return func # return it unchanged return decorator app = App() @app.get("/users")def list_users(): return ["Ada", "Sam"] # Later, when a request arrives:handler = app.routes[("GET", "/users")]print(handler())
Output
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.

Python
EXPORTERS = {} def exporter(fmt): def decorator(func): if fmt in EXPORTERS: raise ValueError(f"duplicate exporter for {fmt!r}") EXPORTERS[fmt] = func return func return decorator @exporter("csv")def to_csv(rows): return "\n".join(",".join(map(str, r)) for r in rows) @exporter("tsv")def to_tsv(rows): return "\n".join("\t".join(map(str, r)) for r in rows) def export(rows, fmt): try: func = EXPORTERS[fmt] except KeyError: raise ValueError(f"unknown format {fmt!r}; have {sorted(EXPORTERS)}") from None return func(rows) print(export([(1, "ada"), (2, "sam")], "csv"))try: export([], "xlsx")except ValueError as e: print(e)
Output
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.

ChallengeMedium

A @retry decorator

Write a decorator factory retry(times, exceptions=(Exception,)).

  • The decorated function is called up to times attempts 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 exceptions must 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 calls
Python
import functools def retry(times: int, exceptions: tuple = (Exception,)): # Return a decorator, which returns a wrapper that loops over attempts. pass
ChallengeEasy

Count 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
Python
import functools def count_calls(func): pass
Key terms
decorator
A callable that takes a function (or class) and returns a replacement. @d above def f means f = 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.