Python decorators explained: from @ syntax to retry and caching
What a decorator really is, how to write one with functools.wraps, decorators that take arguments like @retry(3), and when lru_cache helps or quietly serves stale data.
You've seen them: @property, @dataclass, @app.get("/"), @pytest.fixture. Decorators look
like magic until you realise they're just a function that takes a function and returns another.
The @ is shorthand
@log_calls
def ship(parcel):
...means exactly:
def ship(parcel):
...
ship = log_calls(ship)That's all. The decorator receives the function and returns whatever should be called instead.
Writing one
import functools
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}")
return func(*args, **kwargs)
return wrapper*args, **kwargspass every argument through unchanged.return func(...): forget thereturnand every decorated function returnsNone.@functools.wraps(func)keeps the original name and docstring. Without it,ship.__name__is"wrapper", and so is every other decorated function in your logs.
Decorators with arguments
@retry(3) has one more layer: retry(3) runs first and must return a decorator.
def retry(times, exceptions=(ConnectionError,)):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return func(*args, **kwargs)
except exceptions:
if attempt == times:
raise
return wrapper
return decorator
@retry(3)
def fetch_scans():
...Two details that matter in production: only retry the errors you expect (a ValueError is a bug,
retrying it just hides it three times), and re-raise the last error so the caller still finds out.
You'll write exactly this decorator in the tracking service project on the
Python Developer career path.
Caching with functools
from functools import cache
@cache
def shipping_zone(postcode: str) -> str:
...The first call computes; later calls with the same argument return the stored result. Great for pure functions: same input, same output, no side effects.
It goes wrong when the result depends on something the arguments don't capture:
class EventStore:
@lru_cache(maxsize=None)
def latest(self, parcel_id): # reads the database
...After a new scan is saved, latest() keeps returning the old answer, because nothing tells the
cache the database changed. And because self is part of the key, every store object stays in
memory forever. The fix is usually not a cache at all, but measuring first and adding an index.
Decorators you'll meet
| Decorator | What it does |
|---|---|
@property | a method you read like an attribute |
@staticmethod, @classmethod | methods without self, or with the class |
@dataclass | generates __init__, __repr__, __eq__ |
@functools.cache | remembers results by argument |
@contextlib.contextmanager | a context manager from a generator |
A rule of thumb
Decorators are for behaviour that wraps many functions the same way: logging, timing, retries, access checks. If only one function needs it, write it inside that function. Readers shouldn't have to jump to another file to understand what a call does.
Questions and answers
- What does functools.wraps do in a Python decorator?
- It copies the decorated function's name, docstring and other metadata onto the wrapper. Without it, every decorated function reports itself as 'wrapper', which confuses debugging, logging, documentation tools and tests.
- Why is lru_cache on a method a problem?
- The cache key includes self, so the cache keeps every instance alive as long as the cache exists. It also can't know when the data behind the method changes, so results can go stale. Prefer caching on plain functions of immutable inputs.
Practise it
Read next
- Python generators and iterators, explained with real examples
How iteration works under the hood, how yield turns a function into a lazy generator, how pipelines process files bigger than memory, and the exhaustion trap that catches everyone.
- Python context managers: how with works, and how to write your own
What the with statement guarantees, __enter__ and __exit__ step by step, the contextlib shortcut, and why returning True from __exit__ silently swallows errors.
- Code review checklist for junior developers
What senior engineers look for in a code review, as a practical checklist: correctness, edge cases, tests, naming, structure and performance, with C++-specific points.