Skip to content

11. Decorators and context managers — Cheat sheet

The essentials of module 11 on one page. Every runnable block on this page is checked against its output.

I want to… Use… Example
add behavior to every call of a function a decorator @timed above def load(...)
give a decorator settings a decorator factory @retry(3, [1, 2, 4])
keep the name, docstring and signature @functools.wraps(func) on the wrapper load.__name__ → 'load'
reach the undecorated function func.__wrapped__ or inspect.unwrap(func) load.__wrapped__(path)
see a function’s real parameters inspect.signature(func) (path: str) -> list
match call arguments to parameter names inspect.signature(func).bind(*args, **kwargs) bound.arguments["rate"]
remember results by argument @functools.cache @cache def city(store_id): ...
remember the N most recent results @functools.lru_cache(maxsize=N) f.cache_info(), f.cache_clear()
retry a flaky call with backoff a retry factory with an injected sleep retry(attempts, delays, sleep=waits.append)
register functions in a dict a decorator that returns func unchanged @feature def margin(...)
type a decorator that keeps the signature def deco[**P, R](f: Callable[P, R]) -> Callable[P, R] ParamSpec **P
set up and clean up around a block a context manager with Timer() as t:
write a context manager quickly @contextlib.contextmanager + yield in try/finally with temporary_setting(cfg, "k", 1):
ignore one expected exception contextlib.suppress(Error) with suppress(FileNotFoundError):
capture what a function prints contextlib.redirect_stdout(io.StringIO()) buffer.getvalue()
run code in another folder contextlib.chdir(path) (3.11+) with chdir(tmp):
open a run-time number of files contextlib.ExitStack stack.enter_context(open(p))
make a context manager optional contextlib.nullcontext() cm = lock if threaded else nullcontext()
use one object as decorator and with contextlib.ContextDecorator @watch and with watch:
get a throwaway folder tempfile.TemporaryDirectory() with TemporaryDirectory() as tmp:
Fact Code Note
assign to another name step = drop_returns no parentheses: the object, not a call
store in a dict or list STEPS = {"drop": drop_returns} config-driven pipelines
pass as an argument sorted(rows, key=revenue_of) a callback
return from a function return wrapper closures and decorators
test if callable callable(obj) functions, classes, objects with __call__
__name__, __qualname__ 'load', 'make.<locals>.load' used by logs, registries, frameworks
__doc__, __module__ docstring, '__main__' kept by functools.wraps
__wrapped__ the original function added by functools.wraps
custom attributes wrapper.calls = 0 simple per-function state
import functools
import time
from collections.abc import Callable
TIMINGS: dict[str, float] = {}
def timed[**P, R](func: Callable[P, R]) -> Callable[P, R]: # no arguments
@functools.wraps(func) # keep name, doc, signature; add __wrapped__
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
start = time.perf_counter()
try:
return func(*args, **kwargs) # forward and return
finally:
TIMINGS[func.__name__] = time.perf_counter() - start # always
return wrapper
def round_result[**P]( # with arguments: a factory
digits: int,
) -> Callable[[Callable[P, float]], Callable[P, float]]:
def decorate(func: Callable[P, float]) -> Callable[P, float]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> float:
return round(func(*args, **kwargs), digits)
return wrapper
return decorate
@timed
@round_result(3)
def churn_rate(churned: int, customers: int) -> float:
"""Share of customers who churned."""
return churned / customers
print(churn_rate(963, 5000), churn_rate.__name__, churn_rate.__doc__)
print(TIMINGS["churn_rate"] > 0) # the name came through both layers
Output
0.193 churn_rate Share of customers who churned.
True
def deco(func=None, *, label=None): # works as @deco and @deco(label="x")
def decorate(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
return f(*args, **kwargs)
return wrapper
return decorate if func is None else decorate(func)
REGISTRY = {}
def register(func): # registration: record and return unchanged
REGISTRY[func.__name__] = func
return func
You write Python does
@d above def f f = d(f)
@d(1, x=2) above def f f = d(1, x=2)(f)
@a then @b above def f f = a(b(f)): b wraps first, a runs first
@d above class C C = d(C) (class decorator, e.g. @dataclass)
Decorator Core idea Must have Watch out
timing perf_counter() before and after try/finally; store, do not print, in tests time.time() can jump
retry up to attempts calls in total (first call included), except transient errors a limit, backoff b · 2**(k-1) before retry k, injected sleep, re-raise the last error never retry ValueError/KeyError; only idempotent actions
caching dict keyed by arguments hashable arguments; cache_clear() when data changes side effects are skipped; returned lists are shared
validation check arguments or result, raise early a message with the function name; signature.bind for named arguments assert is removed by python -O
logging print or log name and arguments wraps, so the log shows the real name logging secrets or huge arguments
counting wrapper.calls += 1 initialize the attribute after the inner def counts include cache hits if the counter is outside the cache
from collections.abc import Sequence
waits: list[float] = []
def retry[**P, R](
attempts: int, # total calls, the first one included (as in config.json)
delays: Sequence[float], # delays[k - 1] before retry k
exceptions: tuple[type[Exception], ...] = (ConnectionError, TimeoutError),
sleep: Callable[[float], object] = time.sleep,
) -> Callable[[Callable[P, R]], Callable[P, R]]:
def decorate(func: Callable[P, R]) -> Callable[P, R]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
for attempt in range(1, attempts + 1):
try:
return func(*args, **kwargs)
except exceptions:
if attempt == attempts:
raise # last attempt: the error propagates
sleep(delays[attempt - 1]) # a fake sleep in tests
raise AssertionError("unreachable")
return wrapper
return decorate
calls: list[int] = []
@retry(3, [1, 2, 4], sleep=waits.append)
def fetch() -> str:
calls.append(1)
if len(calls) < 3:
raise ConnectionError("reset")
return "ok"
print(fetch(), len(calls), waits)
Output
ok 3 [1, 2]
Tool Does Example
functools.wraps(func) decorator: copies metadata to the wrapper @functools.wraps(func)
functools.update_wrapper(w, func) the same, as a call return update_wrapper(w, func)
functools.cache unbounded memoization @cache
functools.lru_cache(maxsize=128) bounded memoization, drops least recently used @lru_cache(maxsize=1024)
.cache_info() / .cache_clear() hits, misses, size / empty the cache CacheInfo(hits=95, misses=5, ...)
functools.cached_property compute an attribute once per instance (module 18) @cached_property def stats(self)
functools.partial(f, x=1) a new callable with some arguments fixed partial(round, ndigits=2)
inspect.signature(f) parameters and hints, follows __wrapped__ .parameters, .bind(...)
inspect.unwrap(f) follows __wrapped__ to the original inspect.unwrap(load)
@functools.lru_cache(maxsize=2)
def city(store_id: str) -> str:
return {"S01": "Chicago", "S02": "Minneapolis", "S03": "Detroit"}[store_id]
for sid in ["S01", "S01", "S02", "S03", "S01"]:
city(sid)
print(city.cache_info()) # S01 was evicted by S03, so its last call missed
Output
CacheInfo(hits=1, misses=4, maxsize=2, currsize=2)
Stack (top first) Effect
@timed / @retry one duration that covers all attempts and waits
@retry / @timed one duration per attempt; waits not included
@cache / @timed hits skip the timer; timings show misses only
@timed / @cache every call timed; hits look very fast
@audit_log / @cache every call logged, also cache hits
@cache / @audit_log repeated calls never reach the log
@validate / @cache or the reverse same result for a pure argument check: failed checks raise and are never cached
@app.get(...) / @login_required the framework registers the protected wrapper

Rule: the decorator next to def wraps first; the top one runs first at call time and finishes last.

Case Signature
keeps 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]]
fixed return type def deco[**P](func: Callable[P, float]) -> Callable[P, float]
changes the return type def deco[**P, R](func: Callable[P, R]) -> Callable[P, R | None]
wrapper parameters def wrapper(*args: P.args, **kwargs: P.kwargs) -> R
loose (avoid) Callable[..., Any]: the checker loses the signature
before Python 3.12 P = ParamSpec("P"), R = TypeVar("R") from typing
Step Method Notes
with cm as x: starts x = cm.__enter__() usually return self
block ends normally cm.__exit__(None, None, None)
block raises cm.__exit__(exc_type, exc_value, traceback) runs before the exception continues
__exit__ returns true the exception is suppressed only for errors you handled
__exit__ returns false or None the exception continues the normal case
several managers with a, b: enter a, b; exit b, a
from types import TracebackType
from typing import Self
class Timer:
def __enter__(self) -> Self:
self.start = time.perf_counter()
return self # becomes the "as" name
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: TracebackType | None,
) -> None: # None: never suppresses
self.elapsed = time.perf_counter() - self.start
with Timer() as t:
total = sum(range(100_000))
print(total, t.elapsed > 0)
Output
4999950000 True
from collections.abc import Iterator
from contextlib import contextmanager
from typing import Any
@contextmanager
def temporary_setting(
settings: dict[str, Any], key: str, value: Any
) -> Iterator[dict[str, Any]]:
old = settings[key] # setup = __enter__
settings[key] = value
try:
yield settings # the "as" value; the block runs here
finally:
settings[key] = old # cleanup = __exit__, also after an error
cfg = {"max_quantity": 50}
with temporary_setting(cfg, "max_quantity", 1000):
print(cfg)
print(cfg)
Output
{'max_quantity': 1000}
{'max_quantity': 50}
Want In a @contextmanager function
always clean up try: yield … finally: cleanup
suppress an error type except ValueError: pass around yield, no re-raise
handle and re-raise except Exception: log(); raise
a value for as yield value (exactly one yield)
use as a decorator @temporary_setting(cfg, "k", 1) above a def works too
Tool Does Example
suppress(*errors) swallows the listed exceptions with suppress(FileNotFoundError): os.remove(p)
redirect_stdout(f) print() writes to f with redirect_stdout(buf): noisy()
redirect_stderr(f) the same for sys.stderr capture a tool’s error text
chdir(path) changes the working directory and back (3.11+) with chdir(tmp):
ExitStack() holds any number of managers stack.enter_context(open(p))
stack.callback(f, *args) calls f(*args) at exit stack.callback(print, "done")
stack.pop_all() moves the cleanups to a new stack (keep resources open) return opened files on success
nullcontext(value) does nothing; as gets value optional locks or timers
closing(obj) calls obj.close() at exit old objects with close() only
ContextDecorator base class: a manager that also decorates class Watch(ContextDecorator)
AbstractContextManager base class with a default __enter__ returning self class Timer(AbstractContextManager)
asynccontextmanager contextmanager for async with (module 15) async database sessions
import io
from contextlib import ExitStack, nullcontext, redirect_stdout, suppress
buffer = io.StringIO()
with redirect_stdout(buffer):
print("epoch 1 loss 0.42")
print(repr(buffer.getvalue()))
with suppress(KeyError):
print({"region": "North"}["store"]) # raises KeyError: skipped
print("still running")
with ExitStack() as stack:
stack.callback(print, "closed second")
stack.callback(print, "closed first")
print("in block")
with nullcontext(5) as value:
print(value)
Output
'epoch 1 loss 0.42\n'
still running
in block
closed first
closed second
5
Manager Setup Cleanup
open(path) opens the file closes it
tempfile.TemporaryDirectory() creates a folder deletes it and its contents
tempfile.NamedTemporaryFile() creates a file deletes it (by default)
sqlite3.connect(db) returns the connection commits, or rolls back on error; does not close
threading.Lock() acquires the lock releases it
concurrent.futures.ThreadPoolExecutor() starts worker threads waits for them and shuts down (module 15)
decimal.localcontext() copies the decimal settings restores them
warnings.catch_warnings() saves the warning filters restores them
pd.option_context("display.max_rows", 5) sets pandas options restores them (module 24)
np.errstate(divide="ignore") changes NumPy error handling restores it (module 23)
torch.no_grad() turns off gradient tracking turns it back on (module 42)
pytest.raises(ValueError) expects an exception fails the test if none came (module 14)
  • @factory without parentheses passes the function as the first setting. A factory always needs ().
  • No functools.wraps: every function is named wrapper, and help(), logs and registries break.
  • A wrapper without return turns every result into None.
  • Decorator body code runs at import (decoration time), not at each call.
  • @functools.cache keeps every result forever. Use lru_cache(maxsize=...) for open-ended arguments, and cache_clear() when the data changes.
  • Cached functions need hashable arguments: tuples, not lists.
  • A cached function that returns a list hands every caller the same list object.
  • Retrying except Exception retries bugs. Retry only transient errors, with a limit.
  • with Timer() as t binds the return value of __enter__. No return self means t is None.
  • __exit__ returning True swallows the exception. Returning nothing lets it continue.
  • A @contextmanager function without try/finally around yield skips its cleanup on error.
  • suppress(Exception) around many lines hides bugs. Suppress one type around one line.
  • os.chdir() without a way back breaks every later relative path; use contextlib.chdir.
  • redirect_stdout captures Python’s print() only, not subprocess or C-level output.
  • Several managers in one with exit in reverse order. A sqlite3 connection in with commits but stays open.