Skip to content

Decorators and context managers

Copy-ready templates for decorators and context managers, how they stack, the functools helpers that go with them, and the contextlib toolbox (suppress, ExitStack, redirect_stdout, closing, nullcontext, chdir). Every runnable block is checked against its output.

I want to… Use… Example
run code before and after every call a decorator @log_calls
keep the wrapped function’s name and docstring @functools.wraps(func) on the inner wrapper
pass settings to a decorator a decorator factory (3 levels) @retry(times=3)
allow @deco and @deco(n=2) def deco(func=None, *, n=1): see optional arguments
keep state between calls a class with __call__, or a function attribute @CountCalls
keep the type checker happy ParamSpec: def deco[**P, R](func: Callable[P, R]) -> Callable[P, R] see typed decorators
reach the undecorated function f.__wrapped__ tests, debugging
cache results of a pure function @functools.cache unbounded
cache with a size limit @functools.lru_cache(maxsize=256) f.cache_info(), f.cache_clear()
compute an attribute once per instance @functools.cached_property lazy, then stored
choose an implementation by argument type @functools.singledispatch @fmt.register
register functions in a dict a registry decorator @command("load")
change a class after it is defined a class decorator @dataclass, @register
clean up whatever happens with and a context manager with open(p) as f:
write a context manager quickly @contextlib.contextmanager yield inside try / finally
write a reusable or stateful manager a class with __enter__ / __exit__
ignore one exception type contextlib.suppress(E) with suppress(FileNotFoundError):
open a dynamic number of resources contextlib.ExitStack stack.enter_context(open(p))
register clean-up callbacks stack.callback(func, *args)
capture print output contextlib.redirect_stdout(buffer)
call close() on exit contextlib.closing(obj) old APIs without with
make a manager optional contextlib.nullcontext() lock if threaded else nullcontext()
change the working folder temporarily contextlib.chdir(path) (3.11+)
use a manager as a decorator too contextlib.ContextDecorator @timer() and with timer():
open several managers in one statement parenthesized with (3.10+) with (open(a) as f, open(b) as g):
temporarily change a setting a manager that restores in finally decimal.localcontext(), np.errstate
silence a known warning in one block warnings.catch_warnings() see errors
@decorator
def f(): ...
# is exactly:
def f(): ...
f = decorator(f)
@a
@b
def g(): ...
# is g = a(b(g)): b wraps first, a is the outer layer and runs first
import functools
def log_calls(func):
@functools.wraps(func) # copy __name__, __doc__, __wrapped__
def wrapper(*args, **kwargs):
print(f"-> {func.__name__}{args} {kwargs}")
result = func(*args, **kwargs)
print(f"<- {func.__name__} returned {result!r}")
return result
return wrapper
@log_calls
def add(a, b=0):
"""Add two numbers."""
return a + b
add(2, b=3)
print(add.__name__, add.__doc__, add.__wrapped__(1, 1))
Output
-> add(2,) {'b': 3}
<- add returned 5
add Add two numbers. 2
import functools
def retry(times=3, exceptions=(Exception,)):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return func(*args, **kwargs)
except exceptions as exc:
print(f"attempt {attempt} failed: {exc}")
if attempt == times:
raise
return wrapper
return decorator
calls = {"n": 0}
@retry(times=3, exceptions=(ConnectionError,))
def fetch():
calls["n"] += 1
if calls["n"] < 3:
raise ConnectionError("timeout")
return "data"
print(fetch())
Output
attempt 1 failed: timeout
attempt 2 failed: timeout
data
import functools
def tag(func=None, *, label="INFO"):
if func is None: # called as @tag(label=...)
return functools.partial(tag, label=label)
@functools.wraps(func)
def wrapper(*args, **kwargs):
return f"[{label}] {func(*args, **kwargs)}"
return wrapper
@tag
def hello():
return "hello"
@tag(label="WARN")
def disk():
return "disk 91% full"
print(hello(), disk())
Output
[INFO] hello [WARN] disk 91% full
import functools
class CountCalls:
def __init__(self, func):
functools.update_wrapper(self, func) # the class version of @wraps
self.func = func
self.calls = 0
def __call__(self, *args, **kwargs):
self.calls += 1
return self.func(*args, **kwargs)
@CountCalls
def square(x):
return x * x
print([square(n) for n in range(4)], square.calls, square.__name__)
Output
[0, 1, 4, 9] 4 square

A class-based decorator on a method loses self binding, because the instance is not a descriptor. Use a function decorator for methods, or add __get__.

import functools
import time
from collections.abc import Callable
def timed[**P, R](func: Callable[P, R]) -> Callable[P, R]: # 3.12+ syntax
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
start = time.perf_counter()
try:
return func(*args, **kwargs)
finally:
elapsed = time.perf_counter() - start
print(f"{func.__name__} took less than 1 s: {elapsed < 1}")
return wrapper
@timed
def total(values: list[float], *, scale: float = 1.0) -> float:
return sum(values) * scale
print(total([1.5, 2.5], scale=2))
Output
total took less than 1 s: True
8.0
Case Signature
keep parameters and return type def deco[**P, R](func: Callable[P, R]) -> Callable[P, R]
factory with settings def deco[**P, R](n: int) -> Callable[[Callable[P, R]], Callable[P, R]]
changes the return type def deco[**P, R](func: Callable[P, R]) -> Callable[P, R | None]
adds a first argument Callable[Concatenate[Session, P], R] → Callable[P, R]
wrapper parameters def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
before 3.12 P = ParamSpec("P"), R = TypeVar("R") from typing
avoid Callable[..., Any]: the checker loses the signature
Python 3.10 and 3.11
from typing import Callable, ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")
def timed(func: Callable[P, R]) -> Callable[P, R]: ...
from collections.abc import Callable
COMMANDS: dict[str, Callable[..., str]] = {}
def command(name):
def register(func):
COMMANDS[name] = func # register, return the function unchanged
return func
return register
@command("greet")
def greet(who):
return f"hello {who}"
@command("shout")
def shout(who):
return f"HELLO {who.upper()}"
def add_repr(cls): # a class decorator gets and returns the class
def __repr__(self):
fields = ", ".join(f"{k}={v!r}" for k, v in vars(self).items())
return f"{cls.__name__}({fields})"
cls.__repr__ = __repr__
return cls
@add_repr
class Store:
def __init__(self, store_id, city):
self.store_id, self.city = store_id, city
print(sorted(COMMANDS), COMMANDS["shout"]("ana"), Store("S01", "Chicago"))
Output
['greet', 'shout'] HELLO ANA Store(store_id='S01', city='Chicago')
def deco(name):
def decorator(func):
def wrapper():
print(f"{name} before")
func()
print(f"{name} after")
return wrapper
return decorator
@deco("outer") # applied last, runs first
@deco("inner") # applied first, closest to the function
def work():
print("work")
work()
Output
outer before
inner before
work
inner after
outer after
Stack Typical order (top to bottom)
web route + auth @app.get(...), then @login_required
method decorators @classmethod / @staticmethod / @property on top
caching + logging @log_calls above @cache logs every call; below it logs only cache misses
@pytest.mark... any order; marks only add metadata
Helper Does Note
wraps(func) copies __module__, __name__, __qualname__, __doc__, __annotations__, __type_params__; updates __dict__; sets __wrapped__ always use it in wrappers
update_wrapper(wrapper, func) the function form of wraps class-based decorators
cache unbounded memoization (3.9+) arguments must be hashable
lru_cache(maxsize=128) memoization with least-recently-used eviction maxsize=None is cache
lru_cache(typed=True) caches 1 and 1.0 separately
f.cache_info(), f.cache_clear() statistics, reset
cached_property computes once per instance, then stores in __dict__ not thread-safe; needs __dict__
singledispatch dispatch on the first argument’s type singledispatchmethod for methods
partial(f, *a, **kw) fix some arguments functions page
total_ordering fill in <=, >, >= from __eq__ and __lt__ class decorator
from functools import cache, cached_property, lru_cache, singledispatch
@lru_cache(maxsize=2)
def slow_square(n):
print(f"computing {n}")
return n * n
print([slow_square(n) for n in (2, 2, 3, 4, 2)])
print(slow_square.cache_info())
@cache
def ways(n): # number of ways to climb n stairs with steps of 1 or 2
return 1 if n < 2 else ways(n - 1) + ways(n - 2)
class Report:
def __init__(self, values):
self.values = values
@cached_property
def total(self):
print("summing")
return sum(self.values)
@singledispatch
def fmt(value):
return str(value)
@fmt.register
def _(value: float):
return f"{value:,.2f}"
@fmt.register
def _(value: list):
return " | ".join(fmt(v) for v in value)
r = Report([1, 2, 3])
print(ways(50), r.total, r.total, fmt([1234.5, 7, "x"]))
Output
computing 2
computing 3
computing 4
computing 2
[4, 4, 9, 16, 4]
CacheInfo(hits=1, misses=4, maxsize=2, currsize=2)
summing
20365011074 6 6 1,234.50 | 7 | x
Step Call Detail
enter value = manager.__enter__() value is bound by as
body your block
exit, no error manager.__exit__(None, None, None)
exit, with an error manager.__exit__(exc_type, exc, traceback) return True to suppress the error
with A() as a, B() as b: enters A then B; exits B then A like nested with

The other call and context-manager dunders are in the dunder methods page.

class Transaction:
"""Apply changes to a list; roll them back if the block fails."""
def __init__(self, data):
self.data = data
def __enter__(self):
self.snapshot = list(self.data)
return self.data # bound by `as`
def __exit__(self, exc_type, exc, tb):
if exc_type is not None:
self.data[:] = self.snapshot # roll back
print(f"rolled back after {exc_type.__name__}: {exc}")
return exc_type is ValueError # True suppresses the exception
stock = [5, 3]
with Transaction(stock) as items:
items.append(10)
with Transaction(stock) as items:
items.append(-1)
raise ValueError("negative stock")
print(stock)
Output
rolled back after ValueError: negative stock
[5, 3, 10]
from contextlib import contextmanager
@contextmanager
def section(title):
print(f"== {title} ==") # __enter__ part
try:
yield title.upper() # the value bound by `as`; the block runs here
except KeyError as exc: # handle (and suppress) chosen errors
print("missing key:", exc)
finally:
print(f"== end {title} ==") # always runs: clean-up
with section("load") as name:
print("working in", name)
with section("lookup"):
print({}["store"])
Output
== load ==
working in LOAD
== end load ==
== lookup ==
missing key: 'store'
== end lookup ==
Rule Detail
yield exactly once a second yield raises RuntimeError
put yield in try / finally otherwise clean-up is skipped when the block raises
re-raise by default an exception you do not catch propagates; one you catch is suppressed
it is also a decorator @section("x") on a function wraps each call
Tool Does Example
contextmanager build a manager from a generator above
asynccontextmanager the same for async with async database sessions
suppress(*errors) swallow the listed exceptions with suppress(FileNotFoundError): os.remove(p)
ExitStack() manage a dynamic number of managers files = [stack.enter_context(open(p)) for p in paths]
stack.callback(f, *args) call f at exit (LIFO)
stack.pop_all() move clean-ups to a new stack keep resources open on success
redirect_stdout(f), redirect_stderr(f) send print / errors to f capture library output
closing(obj) call obj.close() at exit with closing(urlopen(url)) as page:
aclosing(obj) call await obj.aclose() async generators
nullcontext(value) do nothing; as gets value optional managers
chdir(path) change the working directory, then restore it (3.11+) not thread-safe
ContextDecorator base class: usable as with and as @
AbstractContextManager base class; default __enter__ returns self
import io
from contextlib import ExitStack, chdir, closing, nullcontext, redirect_stdout, suppress
from pathlib import Path
from tempfile import TemporaryDirectory
buffer = io.StringIO()
with redirect_stdout(buffer):
print("captured line")
print(repr(buffer.getvalue()))
with suppress(FileNotFoundError):
Path("missing.txt").unlink() # no error if the file is missing
print("still running")
paths = ["a.txt", "b.txt"]
with ExitStack() as stack:
files = [stack.enter_context(open(p, "w", encoding="utf-8")) for p in paths]
stack.callback(print, "callback runs first (LIFO), then the files close")
for f in files:
f.write("x")
print([f.closed for f in files], [Path(p).read_text() for p in paths])
class Resource:
def close(self):
print("Resource.close() called")
with closing(Resource()):
pass
lock = None # e.g. threading.Lock() when running in threads
with lock or nullcontext():
print("no lock needed")
with TemporaryDirectory() as tmp, chdir(tmp):
Path("inside.txt").write_text("hi", encoding="utf-8")
print("inside:", sorted(p.name for p in Path().iterdir()))
print("back:", Path("inside.txt").exists())
Output
'captured line\n'
still running
callback runs first (LIFO), then the files close
[True, True] ['x', 'x']
Resource.close() called
no lock needed
inside: ['inside.txt']
back: False
from contextlib import ContextDecorator
class announce(ContextDecorator):
def __init__(self, label):
self.label = label
def __enter__(self):
print(f"start {self.label}")
return self
def __exit__(self, *exc):
print(f"stop {self.label}")
return False # do not suppress errors
@announce("job") # as a decorator
def job():
print("working")
job()
with announce("block"): # as a context manager
print("inline")
Output
start job
working
stop job
start block
inline
stop block
Manager Guarantees
open(path) the file is closed
tempfile.TemporaryDirectory() / NamedTemporaryFile() the folder or file is deleted
threading.Lock() the lock is released
sqlite3.connect(db) commit on success, rollback on error (it does not close; wrap in closing)
decimal.localcontext() precision and rounding restored
warnings.catch_warnings() warning filters restored
unittest.mock.patch(...) the original object restored
pytest.raises(E) the block must raise E
np.errstate(divide="ignore") NumPy error settings restored
pd.option_context("display.max_rows", 5) pandas options restored
torch.no_grad() gradient tracking restored
zipfile.ZipFile, tarfile.open archive closed
concurrent.futures.ThreadPoolExecutor() workers shut down, waits for tasks
httpx.Client() / requests.Session() connections closed
Trap Symptom Fix
no @functools.wraps f.__name__ is wrapper; docs and help() are wrong always wrap the inner function
wrapper does not return the decorated function returns None return func(*args, **kwargs)
a sync wrapper on an async def the wrapper returns the coroutine at once: timing or retry code never sees the real work make the wrapper async def and await func(...); branch on inspect.iscoroutinefunction(func)
@retry without parentheses on a factory TypeError or a function that never runs @retry(), or support both forms
decorator runs at import time side effects (prints, registration) at import intended for registries; keep other work in the wrapper
wrong stacking order @staticmethod under another decorator fails or misbehaves put @classmethod, @staticmethod, @property on top
@cache on a method keeps every self alive (memory leak) cache a module function, or use cached_property
@cache with list or dict arguments TypeError: unhashable type: 'list' pass tuples or frozensets
@cache on impure functions stale results (time, files, random) cache only pure functions
a class-based decorator on a method self is not passed function decorator, or implement __get__
Callable[..., Any] in a typed decorator the checker loses parameter types ParamSpec
@contextmanager without try / finally clean-up skipped when the block raises wrap yield in try / finally
__exit__ returns a truthy value by accident exceptions vanish silently return None or False unless you mean to suppress
suppress(Exception) hides real bugs list the narrow exceptions you expect
with sqlite3.connect(db) as con: the connection stays open with closing(sqlite3.connect(db)) as con, con:
with open(a) as f, open(b) as g: over 88 chars hard to read parenthesized with (...) (3.10+)
chdir in threads or async code other code sees the changed folder pass paths instead
one @contextmanager object used in two with blocks AttributeError: '_GeneratorContextManager' object has no attribute 'args' call the function again for each with