Python · Lesson 9
Decorators
Functions as values, writing decorators and why functools.wraps matters, decorators with arguments, stacking order, decorators that keep state, class-based decorators, functools.cache and lru_cache, singledispatch, property and classmethod, class decorators, and the everyday uses (retry, timing, caching, access checks, registration).
In short
@dmeansf = d(f), once, at definition time- Always
@functools.wraps(func)on the wrapper - Arguments mean three levels: factory, decorator, wrapper
- Stacked: applied bottom-up, run top-down
functools.cacheneeds hashable arguments
A decorator is the @something line above a function. It looks like an annotation, and in C# the similar
[Authorize] attribute is only an annotation: metadata that does nothing until a framework reads it. In
Python, a decorator is code that runs. It receives the function, and whatever it returns replaces the
function. That one idea gives you logging, timing, caching, retries, access checks and route registration
without touching the function's body.
Flask's @app.route, FastAPI's @app.get, pytest's @pytest.fixture, Django's @login_required,
@dataclass, @property and @functools.cache are all decorators. Interviews ask you to write one (a timer, a
retry, a memoizer), to explain functools.wraps, and to predict the order of stacked decorators.
Every python snippet has a ▶ Try button. Predict the output first, then run it.
Functions are values
Everything rests on this: a function is an object like any other. You can assign it, store it in a dict, pass it to another function, and return it from one.
def shout(text: str) -> str:
return text.upper() + "!"
say = shout # no call: the function itself
print(say("hi"), say is shout, say.__name__)
handlers = {"shout": shout, "quiet": str.lower}
print(handlers["quiet"]("HEY"))
print(sorted(["bob", "Al", "cy"], key=str.lower)) # passing a function
A function defined inside another function is a closure: it remembers the variables of the scope it was
created in, even after that scope has returned. nonlocal lets it reassign them.
def make_counter():
count = 0
def increment() -> int:
nonlocal count
count += 1
return count
return increment
a = make_counter()
b = make_counter()
a()
a()
print(a(), b()) # each counter has its own count
That's all a decorator needs: a function that takes a function and returns a new function that closes over the
original. JavaScript developers write the same thing as const logged = withLogging(fn); Python adds the @
syntax so you don't repeat the name.
Writing a decorator
def logged(func):
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}{args}")
result = func(*args, **kwargs)
print(f"{func.__name__} returned {result}")
return result
return wrapper
@logged
def add(a, b):
return a + b
print(add(2, 3))
@logged above def add means exactly add = logged(add). The name add now points at wrapper, and wrapper
calls the original through the closure variable func. *args, **kwargs accept any arguments and pass them on
unchanged, so one decorator fits every function.
The decorator runs once, when the def statement runs (usually at import time), not on each call:
def announce(func):
print("decorating", func.__name__)
return func
@announce
def ping():
return "pong"
print("defined")
print(ping(), ping())
That's why registering decorators (routes, event handlers, plugins) work: the registration happens when the module is imported.
functools.wraps, and why
The wrapper above has a problem you don't see until you look:
def logged(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@logged
def fetch_user(user_id: int) -> dict:
"""Load one user from the database."""
return {"id": user_id}
print(fetch_user.__name__, fetch_user.__doc__)
The decorated function now calls itself wrapper and has lost its docstring. Every log line or tool that prints
__name__ reports wrapper (tracebacks are unaffected: they show the code's own names either way). Worse, frameworks that use the name or signature break: Flask
derives endpoint names from __name__, so two routes decorated this way collide; FastAPI and pytest read the
signature to inject parameters and see (*args, **kwargs).
functools.wraps(func) is itself a decorator, applied to the wrapper. It copies __name__, __qualname__,
__doc__, __module__, __annotations__ and the function's attribute dict onto the wrapper, and sets
__wrapped__ to the original:
import functools
import inspect
def logged(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@logged
def fetch_user(user_id: int) -> dict:
"""Load one user from the database."""
return {"id": user_id}
print(fetch_user.__name__, "-", fetch_user.__doc__)
print(inspect.signature(fetch_user)) # follows __wrapped__
print(fetch_user.__wrapped__(7)) # the undecorated original
Rule: every wrapper gets @functools.wraps(func). It costs one line, and __wrapped__ also lets tests
call the original function without the decorator's behavior.
Decorators with arguments: three levels
@retry(times=3) has parentheses, so the expression after @ is a call that runs first and must return
the actual decorator. That's one more level of nesting:
import functools
def repeat(times: int):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return [func(*args, **kwargs) for _ in range(times)]
return wrapper
return decorator
@repeat(3)
def roll() -> str:
return "dice"
print(roll())
| Level | Runs | Receives | Returns |
|---|---|---|---|
repeat(times) | once, when the @ line is evaluated | the decorator's arguments | decorator |
decorator(func) | once, right after, at definition time | the function | wrapper |
wrapper(*args, **kwargs) | on every call | the call's arguments | the result |
Each level closes over the ones outside it, so wrapper can use both times and func. The classic mistake
is forgetting the parentheses:
import functools
def repeat(times: int):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return [func(*args, **kwargs) for _ in range(times)]
return wrapper
return decorator
@repeat # no (3): repeat receives the function as `times`
def roll() -> str:
return "dice"
try:
print(roll())
except TypeError as e:
print("TypeError:", e)
roll is now repeat(roll), which is decorator, so calling roll() calls decorator() with no function.
Libraries that accept both @retry and @retry(times=5) check whether the first argument is callable:
import functools
def retry(func=None, *, times: int = 3):
if func is None: # used as @retry(times=...)
return functools.partial(retry, times=times)
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return func(*args, **kwargs)
except ConnectionError:
if attempt == times:
raise
print(f"attempt {attempt} failed, retrying")
return wrapper
calls = {"n": 0}
@retry(times=3)
def flaky() -> str:
calls["n"] += 1
if calls["n"] < 3:
raise ConnectionError("reset")
return "ok"
@retry
def stable() -> str:
return "fine"
print(flaky(), stable())
Stacking order
Several decorators stack. They're applied bottom-up (the one nearest the def first) and run top-down
on each call (the top one is the outermost wrapper):
import functools
def trace(label):
def decorator(func):
print("applying", label)
@functools.wraps(func)
def wrapper():
print("enter", label)
result = func()
print("exit", label)
return result
return wrapper
return decorator
@trace("outer")
@trace("inner")
def work():
print("working")
work()
@outer @inner def work is work = outer(inner(work)). Think of layers of an onion: a call goes in through
outer, then inner, reaches work, and comes back out in reverse.
Order changes behavior. Put an access check above a cache, or the cache serves one user's result to the next user without checking them:
import functools
ROLE = {"value": "admin"}
def admin_only(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if ROLE["value"] != "admin":
raise PermissionError("admins only")
return func(*args, **kwargs)
return wrapper
@functools.cache
@admin_only
def salary_report() -> str:
return "secret numbers"
print(salary_report())
ROLE["value"] = "guest"
print(salary_report()) # served from the cache: the check never ran
Swap the two lines (@admin_only on top) and the second call raises PermissionError.
Decorators that keep state
A decorator can keep data between calls. The simplest place is an attribute on the wrapper (functions are objects); each decorated function gets its own wrapper, so its own count:
import functools
def count_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
wrapper.calls += 1
return func(*args, **kwargs)
wrapper.calls = 0
return wrapper
@count_calls
def send_email(to: str) -> None:
pass
@count_calls
def send_sms(to: str) -> None:
pass
for user in ["ann", "bob", "cy"]:
send_email(user)
send_sms("ann")
print(send_email.calls, send_sms.calls)
Closure variables with nonlocal work too, and keep the state private. The state lives as long as the
decorated function, which is usually the whole process, so it's shared by every caller and every thread. In a
web server that's often what you want (a cache, a rate limiter) and sometimes a bug (per-request data).
Class-based decorators
Anything callable can be a decorator, including an object whose class has __call__. A class is handy when
the state deserves methods and a readable name:
import functools
class CountCalls:
def __init__(self, func) -> None:
functools.update_wrapper(self, func) # wraps, for an object
self.func = func
self.calls = 0
def __call__(self, *args, **kwargs):
self.calls += 1
return self.func(*args, **kwargs)
def reset(self) -> None:
self.calls = 0
@CountCalls
def greet(name: str) -> str:
return f"hi {name}"
greet("ann")
greet("bob")
print(greet.calls, greet.__name__, type(greet).__name__)
Here the instance replaces the function. That has a trap: on a method, a plain object doesn't bind
self, because only functions (and other descriptors) turn into bound methods when looked up on an instance:
import functools
class CountCalls:
def __init__(self, func) -> None:
functools.update_wrapper(self, func)
self.func = func
self.calls = 0
def __call__(self, *args, **kwargs):
self.calls += 1
return self.func(*args, **kwargs)
class Greeter:
@CountCalls
def hello(self) -> str:
return "hi"
try:
Greeter().hello()
except TypeError as e:
print("TypeError:", e)
The other style avoids it: the instance is the decorator, configured in __init__, and __call__(self, func) returns an ordinary function wrapper. That's the shape of the Circuit breaker exercise, where one
breaker object guards several functions and exposes its state.
functools.cache and lru_cache
Memoization is the decorator everyone uses. @functools.cache stores every result by its arguments;
@functools.lru_cache(maxsize=128) keeps only the most recently used entries:
from functools import cache
@cache
def fib(n: int) -> int:
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(80))
print(fib.cache_info())
Without the cache, fib(80) makes more than 10^16 calls and never finishes; with it, there are 81 misses
(one per value of n) and 78 hits. Both decorators add
cache_info() and cache_clear().
The arguments must be hashable, because they become a dict key. Lists, dicts and sets raise TypeError;
pass tuples or frozensets instead:
from functools import cache
@cache
def total(prices) -> int:
return sum(prices)
print(total((1, 2, 3)))
try:
total([1, 2, 3])
except TypeError as e:
print("TypeError:", e)
More rules worth knowing:
f(1, 2)andf(1, b=2)are different cache entries, even though they mean the same.- The cached object is shared. Mutating a returned list or dict changes what every later caller gets:
from functools import cache
@cache
def default_settings() -> dict:
return {"retries": 3}
settings = default_settings()
settings["retries"] = 99 # mutates the cached dict
print(default_settings())
- On a method,
@cachekeys onselftoo and keeps every instance alive as long as the cache does. For per-object caching usefunctools.cached_property. - There's no expiry. For "cache for 60 seconds", see the TTL cache exercise or
cachetools.
C# has no built-in memoize attribute (you use IMemoryCache or Lazy<T>); JavaScript has nothing built in
either, and lodash's memoize keys on the first argument only.
functools.singledispatch
singledispatch turns a function into one that picks an implementation by the type of its first
argument, at runtime. It's Python's answer to method overloading, and it's open: other modules can register
more types later.
from datetime import date
from decimal import Decimal
from functools import singledispatch
@singledispatch
def to_json(value):
raise TypeError(f"can't serialize {type(value).__name__}")
@to_json.register
def _(value: str) -> str:
return value
@to_json.register
def _(value: int) -> int:
return value
@to_json.register
def _(value: date) -> str:
return value.isoformat()
@to_json.register
def _(value: Decimal) -> str:
return str(value)
@to_json.register(list)
@to_json.register(tuple)
def _(value) -> list:
return [to_json(v) for v in value]
print(to_json([date(2026, 10, 1), Decimal("9.99"), ("a", 1), True]))
try:
to_json({1, 2})
except TypeError as e:
print("TypeError:", e)
register reads the type from the annotation, or takes it as an argument. Dispatch follows inheritance: True
is a bool, a subclass of int, so the int version handles it. In C#, overloads are chosen at compile time
from the declared type; singledispatch chooses at runtime from the actual type. For methods, use
functools.singledispatchmethod.
Method decorators: property, classmethod, staticmethod
The decorators you see most in classes are built in. A quick recap:
class Temperature:
def __init__(self, celsius: float) -> None:
self.celsius = celsius
@property
def fahrenheit(self) -> float: # read like an attribute
return self.celsius * 9 / 5 + 32
@fahrenheit.setter
def fahrenheit(self, value: float) -> None:
self.celsius = (value - 32) * 5 / 9
@classmethod
def from_fahrenheit(cls, value: float) -> "Temperature": # alternative constructor
return cls((value - 32) * 5 / 9)
@staticmethod
def is_valid(celsius: float) -> bool: # no self, no cls
return celsius >= -273.15
t = Temperature.from_fahrenheit(212)
print(t.celsius, t.fahrenheit)
t.fahrenheit = 32
print(t.celsius, Temperature.is_valid(-300))
@property is C#'s get/set and TypeScript's get/set accessors. @classmethod receives the class, so
from_fahrenheit also builds subclasses correctly; @staticmethod is a plain function namespaced in the class.
Your own function decorators work on methods unchanged: self is just the first positional argument, and it
goes through *args.
Class decorators
A decorator can also receive a class. It runs when the class statement finishes, and it returns the class
(modified or not). @dataclass is the famous one: it reads the annotations and writes __init__, __repr__
and __eq__ for you. A registry is the everyday homemade one:
EXPORTERS: dict[str, type] = {}
def exporter(fmt: str):
def decorator(cls: type) -> type:
EXPORTERS[fmt] = cls
return cls
return decorator
@exporter("csv")
class CsvExporter:
def export(self, rows: list) -> str:
return "\n".join(",".join(map(str, r)) for r in rows)
@exporter("tsv")
class TsvExporter:
def export(self, rows: list) -> str:
return "\n".join("\t".join(map(str, r)) for r in rows)
print(sorted(EXPORTERS))
print(EXPORTERS["csv"]().export([[1, 2], [3, 4]]))
TypeScript developers know this shape from Angular's @Component and @Injectable, which attach metadata to
a class. TypeScript 5 decorators are close to Python's: functions that receive the target and may return a
replacement.
Real uses
A short tour of what decorators are for in production code. The exercises build most of these properly.
| Use | What the decorator does | Library examples |
|---|---|---|
| Retry | catch listed exceptions, sleep with backoff, try again | tenacity, backoff |
| Timing and metrics | read a clock before and after, report the duration | Prometheus @histogram.time(), OpenTelemetry |
| Memoize | look up arguments in a dict before calling | functools.cache, cachetools |
| Access checks | inspect the user, raise before calling | Django @login_required, @permission_required |
| Registration | store the function in a registry, return it unchanged | Flask @app.route, atexit.register |
| Validation and conversion | check or convert arguments and results | pydantic @validate_call |
pytest's @fixture, Celery's @app.task and Click's @command also register, but return a wrapper object
instead of the function.
A timing decorator, with the clock injected so the output is predictable:
import functools
def timed(clock):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = clock()
try:
return func(*args, **kwargs)
finally:
print(f"{func.__name__} took {clock() - start:.1f}s")
return wrapper
return decorator
ticks = iter([0.0, 1.5, 10.0, 10.2])
@timed(lambda: next(ticks))
def build_report() -> str:
return "report.pdf"
print(build_report())
print(build_report())
In production you pass time.perf_counter. Taking dependencies like the clock or sleep as parameters is what
makes decorators testable, and every decorator exercise in this topic does it.
Async functions need an async wrapper: async def wrapper(*args, **kwargs): return await func(*args, **kwargs). A plain wrapper would return the coroutine without awaiting it, so timing and retries would measure
nothing. Libraries check inspect.iscoroutinefunction(func) and pick the right wrapper.
Interview checklist
@dabovedef fmeansf = d(f), run once at definition time.- Always
@functools.wraps(func)on the wrapper; know what it copies and that it sets__wrapped__. - Decorators with arguments have three levels;
@dwithout()passes the function as the first argument. - Stacked decorators apply bottom-up and run top-down:
@a @b def fisa(b(f)). - State in a decorator is shared by every call of that function, across threads.
functools.cacheneeds hashable arguments and shares the returned object.- A class instance used as a wrapper doesn't bind
selfon methods; a function wrapper does.
Practise this lesson
In the app: a short video, 7 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.
Open in the app