Advanced Python · Lesson 35 of 39
Decorators and Context Managers
You have already used decorators – @property, @dataclass, @lru_cache – and context managers – with open(...). Both are ways to wrap extra behaviour around your code without changing the code itself. Web frameworks use decorators for routes (@app.get("/")), and testing tools use them everywhere. Here is how they work and how to write your own.
In this lesson
- The building blocks: functions as values and closures
- Writing a decorator and using the
@syntax functools.wrapsand decorators with arguments- Context managers with
@contextmanager
Building block: a function that returns a function
def make_multiplier(factor):
def multiply(n):
return n * factor # remembers factor: a closure
return multiply
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(10), triple(10))
20 30
A decorator uses exactly this idea: it takes a function and returns a new function that wraps it.
Your first decorator
def announce(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
@announce
def add(a, b):
return a + b
add(2, 3)
→ calling add(2, 3) ← add returned 5
@announce above the def is just a short way of writing add = announce(add). From then on, the name add refers to wrapper, which calls the original add in the middle.
Calling a decorated function
- add(2, 3)actually calls wrapper(2, 3)
- Beforewrapper runs its extra code
- func(*args, **kwargs)the original add runs
- Afterwrapper runs more code and returns the result
*args, **kwargs let the wrapper accept any arguments and pass them through unchanged, so one decorator works on any function.
A practical decorator: timing
import time
from functools import wraps
def timed(func):
@wraps(func) # keep the original name and docstring
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"{func.__name__} took {elapsed:.1f}s")
return result
return wrapper
@timed
def build_report():
"""Pretend to do slow work."""
time.sleep(0.2)
return "report ready"
print(build_report())
print(build_report.__name__, "|", build_report.__doc__)
build_report took 0.2s report ready build_report | Pretend to do slow work.
Common mistake: forgetting @wraps
Without @functools.wraps(func), the decorated function's name becomes wrapper and its docstring disappears, which confuses debuggers, documentation tools and frameworks. Always add it.
Decorators with arguments
To pass settings, add one more layer: a function that takes the settings and returns the actual decorator.
from functools import wraps
def retry(times):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return func(*args, **kwargs)
except ConnectionError as error:
print(f"attempt {attempt} failed: {error}")
raise ConnectionError(f"gave up after {times} attempts")
return wrapper
return decorator
calls = {"n": 0}
@retry(times=3)
def fetch_rates():
calls["n"] += 1
if calls["n"] < 3:
raise ConnectionError("timeout")
return {"USD": 84.2}
print(fetch_rates())
attempt 1 failed: timeout
attempt 2 failed: timeout
{'USD': 84.2}Where you'll see decorators
| Decorator | What it adds |
|---|---|
@property, @classmethod, @staticmethod | special method types in classes |
@dataclass | generated __init__, __repr__, __eq__ |
@functools.lru_cache | remembers results (memoisation) |
@app.get("/users") (FastAPI, Flask) | registers a function as a web route |
@pytest.mark.parametrize | runs a test with many inputs |
Context managers: with
A context manager runs set-up code when a with block starts and clean-up code when it ends – even if an error occurs. open() is one; you can write your own easily with @contextmanager. Code before yield is the set-up, code after it is the clean-up:
from contextlib import contextmanager
import time
@contextmanager
def stopwatch(label):
start = time.perf_counter()
try:
yield
finally:
print(f"{label}: {time.perf_counter() - start:.1f}s")
with stopwatch("loading data"):
time.sleep(0.3)
print("after the block")
loading data: 0.3s after the block
A context manager can also hand a value to the as name and guarantee clean-up when things fail:
from contextlib import contextmanager
@contextmanager
def transaction(db):
print("BEGIN")
try:
yield db
print("COMMIT")
except Exception:
print("ROLLBACK")
raise
accounts = {"asha": 500}
try:
with transaction(accounts) as db:
db["asha"] -= 800
if db["asha"] < 0:
raise ValueError("overdrawn")
except ValueError as error:
print("error:", error)
BEGIN ROLLBACK error: overdrawn
(A real database library would also undo the change on rollback; here we only print the steps.)
Practice
Try it yourself
Write a decorator
@uppercasethat converts a function's string result to upper case.Show solution
from functools import wraps def uppercase(func): @wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs).upper() return wrapper @uppercase def greet(name): return f"hello, {name}" print(greet("tara"))HELLO, TARA
Write a decorator that counts how many times a function has been called and stores it in
wrapper.calls.Show solution
from functools import wraps def count_calls(func): @wraps(func) def wrapper(*args, **kwargs): wrapper.calls += 1 return func(*args, **kwargs) wrapper.calls = 0 return wrapper @count_calls def ping(): return "pong" ping(); ping(); ping() print(ping.calls)3
Quick check
What is @deco above def f equivalent to?
f = deco(f)
Why use *args, **kwargs in a wrapper?
So the wrapper accepts and forwards any arguments, making the decorator work with any function.
In a @contextmanager function, when does the code after yield run?
When the with block ends (put it in finally so it also runs after an error).
Summary
- A decorator takes a function and returns a wrapper;
@decomeansf = deco(f). - Use
*args, **kwargsand@functools.wrapsin every wrapper. - Add an outer function for decorators with arguments.
- Context managers wrap set-up and clean-up around a
withblock.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.