11. Decorators and context managers
Data pipelines repeat the same chores around every step. Time it. Retry it when the network fails. Cache its result. Check its input. Open a file and close it again. Change a setting and put it back. This module gives you two tools that write each chore once and apply it everywhere: decorators wrap a function with extra behavior, and context managers wrap a block of code with setup and cleanup.
What you will learn
Section titled “What you will learn”- Treat functions as objects: store them, pass them, return them and read their metadata.
- Write decorators without and with arguments, keep the wrapped function’s name and docstring with
functools.wraps, and type them withCallable[P, R]. - Build the four classic pipeline decorators: timing, retry with backoff, caching and input validation.
- Predict the order in which stacked decorators run.
- Use
with, and write your own context managers as classes (__enter__and__exit__) and withcontextlib.contextmanager. - Use the
contextlibtoolbox:suppress,redirect_stdout,chdirandExitStack.
Prerequisites
Section titled “Prerequisites”- 05. Functions:
*argsand**kwargs, higher-order functions and closures. Decorators are closures. - 06. Errors and debugging:
try,except,finallyandraise. - 07. Files and data formats:
with open(...),pathliband thecsvandjsonmodules. - 09. Standard library power tools:
functools.lru_cacheandcache. - 10. Iterators and generators:
yield. Generator-based context managers use it.
Concepts
Section titled “Concepts”Functions are objects
Section titled “Functions are objects”Module 05 showed that a function is an object. You can give it another name, put it in a list or a dict, pass it to another function and return it from a function. A function object also carries metadata: data about the function itself, stored as attributes.
| Attribute | Holds | Example value |
|---|---|---|
__name__ |
the name in the def line |
'drop_returns' |
__doc__ |
the docstring, or None |
'Remove lines with quantity <= 0.' |
__qualname__ |
the name with its enclosing function or class | 'make_check.<locals>.check' |
__module__ |
the module that defined it | '__main__' |
A pipeline can use these objects directly. Here a config lists the cleaning steps by name, and a dict maps each name to its function:
def drop_returns(quantities: list[int]) -> list[int]: """Remove lines with quantity <= 0.""" return [q for q in quantities if q > 0]
def cap_bulk(quantities: list[int]) -> list[int]: """Cap bulk lines at 50 units (config.json max_quantity).""" return [min(q, 50) for q in quantities]
STEPS = {"drop_returns": drop_returns, "cap_bulk": cap_bulk}config_steps = ["drop_returns", "cap_bulk"]
quantities = [1, 2, -3, 1, 250, 4]for name in config_steps: step = STEPS[name] quantities = step(quantities) print(f"{step.__name__}: {step.__doc__}")print(quantities)print(callable(step), callable(quantities))drop_returns: Remove lines with quantity <= 0.cap_bulk: Cap bulk lines at 50 units (config.json max_quantity).[1, 2, 1, 50, 4]True FalseSTEPS[name] returns a function object, and step(quantities) calls it. The built-in callable() tells you if you can call an object with parentheses. A callable is any such object: a function, a class or an object with a __call__ method. The step names in the report come from __name__, not from a second list that you must keep in sync. Keep this in mind: the next sections show how a careless decorator breaks exactly this.
Wrap a function by hand
Section titled “Wrap a function by hand”Say you want every pipeline step to report when it starts and ends. You could add two print() lines to every step. A better way writes the extra behavior once, in a function that takes a step and returns a new, wrapped step:
def log_calls(func): def wrapper(*args, **kwargs): print(f"start {func.__name__}") result = func(*args, **kwargs) print(f"end {func.__name__}") return result
return wrapper
def mean_revenue(revenues: list[float]) -> float: """Average revenue per sales line.""" return round(sum(revenues) / len(revenues), 2)
mean_revenue = log_calls(mean_revenue)print(mean_revenue([66.49, 14.99, 129.95]))start mean_revenueend mean_revenue70.48log_calls receives the function object mean_revenue and defines wrapper, a closure that remembers func. The line mean_revenue = log_calls(mean_revenue) replaces the name with the wrapper. Every later call goes through the wrapper, which prints, calls the original, prints again and passes the result back.
Three parts make this work:
*args, **kwargsin the wrapper accepts any arguments.func(*args, **kwargs)forwards them unchanged, so the wrapper fits any function.return resultpasses the original return value back. Forget it and every wrapped function returnsNone.- The closure keeps
funcalive afterlog_callshas returned.
A function that wraps another like this is a wrapper function. A callable that takes a function and returns a replacement for it is a decorator. log_calls is a decorator.
The @ syntax
Section titled “The @ syntax”Python has a short form for mean_revenue = log_calls(mean_revenue). Write @log_calls on the line above the def:
@log_callsdef max_revenue(revenues: list[float]) -> float: return max(revenues)
print(max_revenue([66.49, 14.99, 129.95]))start max_revenueend max_revenue129.95The two forms do exactly the same thing. The @ form is easier to read, because the decoration sits next to the name, and the undecorated function never exists under its own name.
The decorator runs once, when Python executes the def statement. This moment is decoration time. The wrapper runs at every call. This is call time. The difference matters. Code in the decorator body (outside the wrapper) runs when the module is imported, before any data arrives:
def announce(func): print(f"decorating {func.__name__}") return func
@announcedef load_orders(): return ["O000001", "O000002"]
print("module loaded")print(load_orders())decorating load_ordersmodule loaded['O000001', 'O000002']flowchart LR
D["def + @decorator<br/>(decoration time, once)"] --> W["name now points<br/>to the wrapper"]
W --> C["each call<br/>(call time)"]
C --> B["wrapper: code before"]
B --> F["original function"]
F --> A["wrapper: code after"]
A --> R["return value"]
functools.wraps keeps the metadata
Section titled “functools.wraps keeps the metadata”The wrapper replaced the function, so the name mean_revenue now refers to wrapper. Look at its metadata:
print(mean_revenue.__name__)print(mean_revenue.__doc__)wrapperNoneThe original name and docstring are gone. This breaks real things. A pipeline report that prints step.__name__ shows wrapper for every step. help(mean_revenue) shows no documentation. Test tools, web frameworks and loggers that look up functions by name get the wrong name. Two steps decorated by the same decorator even look identical.
functools.wraps fixes this. It is itself a decorator: put @functools.wraps(func) on the wrapper, and it copies __name__, __doc__, __qualname__, __module__ and the type hints from func to the wrapper. It also adds the attribute __wrapped__, which points to the original function.
import functoolsimport inspect
def log_calls(func): @functools.wraps(func) def wrapper(*args, **kwargs): print(f"start {func.__name__}") result = func(*args, **kwargs) print(f"end {func.__name__}") return result
return wrapper
@log_callsdef mean_revenue(revenues: list[float]) -> float: """Average revenue per sales line.""" return round(sum(revenues) / len(revenues), 2)
print(mean_revenue.__name__)print(mean_revenue.__doc__)print(inspect.signature(mean_revenue))print(mean_revenue.__wrapped__([66.49, 14.99, 129.95]))mean_revenueAverage revenue per sales line.(revenues: list[float]) -> float70.48inspect.signature() follows __wrapped__, so it shows the real parameters. Calling __wrapped__ runs the original function without the wrapper, which is handy in tests: no start and end lines appear. Use @functools.wraps(func) in every decorator you write. It costs one line.
Decorators with arguments
Section titled “Decorators with arguments”log_calls has no settings. Many decorators need some: how many times to retry, how many decimals to round to, which columns to require. You write @round_result(2) with arguments. Python first calls round_result(2), and the result must be a decorator. So you need one more level of function:
def round_result(digits): def decorate(func): @functools.wraps(func) def wrapper(*args, **kwargs): return round(func(*args, **kwargs), digits)
return wrapper
return decorate
@round_result(2)def churn_rate(churned: int, customers: int) -> float: return churned / customers
print(churn_rate(963, 5000))print(churn_rate.__name__)0.19churn_rateThe outer function is a decorator factory: a function that takes settings and returns a decorator. Read the three levels from the outside in:
| Level | Called | Receives | Returns |
|---|---|---|---|
round_result(digits) |
once, when @round_result(2) runs |
the settings | decorate |
decorate(func) |
once, right after | the function | wrapper |
wrapper(*args, **kwargs) |
at every call | the call’s arguments | the (rounded) result |
@round_result(2) above def churn_rate means churn_rate = round_result(2)(churn_rate). The churn rate of data/customers.csv is 963 of 5,000 customers, so the rounded result is 0.19.
Decorators with state, and registration decorators
Section titled “Decorators with state, and registration decorators”A wrapper can keep data between calls. The simplest place is an attribute on the wrapper itself, because a function is an object:
def count_calls(func): @functools.wraps(func) def wrapper(*args, **kwargs): wrapper.calls += 1 return func(*args, **kwargs)
wrapper.calls = 0 return wrapper
@count_callsdef parse_reading(text: str) -> float: return float(text)
for raw in ["21.7", "22.1", "21.9"]: parse_reading(raw)print(parse_reading.calls)3A decorator does not have to wrap at all. A registration decorator records the function somewhere and returns it unchanged. Frameworks use this pattern to collect functions: Flask and FastAPI register URL handlers with @app.get("/predict"), pytest collects fixtures with @pytest.fixture and command-line libraries register commands.
FEATURES = {}
def feature(func): FEATURES[func.__name__] = func return func
@featuredef margin(price: float, cost: float) -> float: return round((price - cost) / price, 3)
@featuredef markup(price: float, cost: float) -> float: return round(price / cost, 2)
print(sorted(FEATURES))print({name: f(79.99, 31.50) for name, f in FEATURES.items()})['margin', 'markup']{'margin': 0.606, 'markup': 2.54}The two features use the price and cost of the Wireless Earbuds (P001) from data/products.csv. To add a feature, you write one function with @feature above it. No central list needs an edit.
Stacking decorators
Section titled “Stacking decorators”You can put several decorators on one function. They apply from the bottom up: the decorator nearest the def wraps first. At call time, the outermost (top) wrapper runs first.
def tag(label): def decorate(func): @functools.wraps(func) def wrapper(*args, **kwargs): print(f"enter {label}") result = func(*args, **kwargs) print(f"exit {label}") return result
return wrapper
return decorate
@tag("top")@tag("bottom")def total_units(quantities: list[int]) -> int: print(" computing") return sum(quantities)
print(total_units([1, 2, 1]))enter topenter bottom computingexit bottomexit top4The stack means total_units = tag("top")(tag("bottom")(total_units)). Think of layers of an onion: the call goes in through every layer and comes back out in reverse order.
flowchart LR
caller["call"] --> top["top wrapper<br/>(listed first)"]
top --> bottom["bottom wrapper<br/>(next to def)"]
bottom --> f["total_units"]
f -. "result" .-> bottom
bottom -. "result" .-> top
top -. "result" .-> caller
The order changes the behavior. A timer above a retry measures all the attempts together. A timer below the retry measures each attempt. A cache above a call counter or an audit log hides every repeated call from it. Example 8 shows this with real numbers.
Type hints for decorators
Section titled “Type hints for decorators”Part 2 of the course uses type hints where they help. Decorators are a place where hints help a lot, and also a place where careless hints hide errors. A type hint (module 10) is an annotation such as list[float] that says what type a value should have. Python ignores hints at run time. A type checker such as mypy reads them and reports mismatches before you run the code. Module 12 teaches them in depth.
The obvious hint for a decorator is “takes any callable, returns any callable”:
from collections.abc import Callablefrom typing import Any
def timed_loose(func: Callable[..., Any]) -> Callable[..., Any]: ...It is correct but loses information. After @timed_loose, the type checker knows nothing about the parameters or the return type of the decorated function. Callable[..., Any] means “any arguments, any result”.
A type parameter is a placeholder for a type that the checker fills in at each use. Python 3.12 declares them in square brackets after the function name. Two kinds of type parameter describe a decorator exactly:
Rstands for one type: the return type offunc.**Pis a ParamSpec (parameter specification): it stands for the whole parameter list offunc.P.argsandP.kwargstype the wrapper’s*argsand**kwargs.
def timed[**P, R](func: Callable[P, R]) -> Callable[P, R]: ...Read it as: “timed takes a function with parameters P that returns R, and returns a function with the same parameters and the same return type.” The file below defines both versions, applies them to the same Celsius-to-Fahrenheit function, c_to_f, and has one deliberate mistake for each: the text "32" where a number belongs.
"""Compare a loosely typed decorator with one typed with ParamSpec."""
import functoolsimport timefrom collections.abc import Callablefrom typing import Any
TIMINGS: dict[str, float] = {}
def timed_loose(func: Callable[..., Any]) -> Callable[..., Any]: """Record the duration of each call. The hints hide the signature."""
@functools.wraps(func) def wrapper(*args: Any, **kwargs: Any) -> Any: start = time.perf_counter() try: return func(*args, **kwargs) finally: TIMINGS[func.__name__] = time.perf_counter() - start
return wrapper
def timed[**P, R](func: Callable[P, R]) -> Callable[P, R]: """Record the duration of each call. The hints keep the signature."""
@functools.wraps(func) def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: start = time.perf_counter() try: return func(*args, **kwargs) finally: TIMINGS[func.__name__] = time.perf_counter() - start
return wrapper
@timed_loosedef c_to_f_loose(celsius: list[float], offset: float) -> list[float]: return [round(c * 9 / 5 + offset, 1) for c in celsius]
@timeddef c_to_f(celsius: list[float], offset: float) -> list[float]: return [round(c * 9 / 5 + offset, 1) for c in celsius]
def typo_demo() -> None: """Never called. Both calls pass the text "32" where a float belongs.""" c_to_f_loose([21.5, 22.0], "32") c_to_f([21.5, 22.0], "32")
if __name__ == "__main__": print(c_to_f([21.5, 22.0], 32)) print(sorted(TIMINGS))[70.7, 71.6]['c_to_f']The script runs, because Python does not check hints and typo_demo() is never called. Now ask mypy, which the course requirements install:
mypy typed.pytyped.py:52: error: Argument 2 to "c_to_f" has incompatible type "str"; expected "float" [arg-type]Found 1 error in 1 file (checked 1 source file)mypy finds the mistake on line 52, through the timed decorator. It misses the same mistake on line 51, because timed_loose told it “any arguments”. Use the [**P, R] form for decorators that keep the signature. For a decorator factory, put the type parameters on the factory and return Callable[[Callable[P, R]], Callable[P, R]], as the retry decorator in Example 2 does.
Decorators you already use
Section titled “Decorators you already use”The standard library and the big data libraries ship many decorators. You use them the same way as your own.
| Decorator | From | What it does |
|---|---|---|
@functools.cache |
standard library | remembers every result by its arguments (module 09) |
@functools.lru_cache(maxsize=128) |
standard library | remembers the 128 most recent results |
@functools.wraps(func) |
standard library | copies metadata to a wrapper |
@contextlib.contextmanager |
standard library | turns a generator into a context manager (below) |
@property, @classmethod, @staticmethod |
built in | change how a method in a class behaves (module 18) |
@dataclass |
dataclasses |
writes __init__ and __repr__ for a class (module 21) |
@pytest.fixture, @pytest.mark.parametrize(...) |
pytest | registers test helpers (module 14) |
@app.get("/predict") |
FastAPI | registers a web endpoint (module 44) |
@torch.no_grad() |
PyTorch | turns off gradient tracking in a function (module 42) |
@dataclass decorates a class, not a function. A class decorator takes a class and returns a class. It works the same way as a function decorator.
The with statement and the context manager protocol
Section titled “The with statement and the context manager protocol”Many resources come in pairs of actions: open and close a file, start and stop a timer, change a setting and restore it, begin and commit a database transaction, acquire and release a lock. The second action must happen even when the code in between fails. Module 07 showed that with open(...) as f: closes the file for you. An object that works with with is a context manager.
The with statement follows a fixed set of rules, the context manager protocol. A protocol is a set of methods that an object must have to work with a language feature. This one has two methods:
__enter__(self)runs when thewithblock starts. Its return value is bound to the name afteras.__exit__(self, exc_type, exc_value, traceback)runs when the block ends, normally or with an exception. The three arguments describe the exception, or are allNonewhen there was none. A true return value suppresses the exception.
with manager as name: does roughly this:
name = manager.__enter__()try: ... # the body of the with blockexcept BaseException as exc: if not manager.__exit__(type(exc), exc, exc.__traceback__): raise # __exit__ returned a false value: the error continueselse: manager.__exit__(None, None, None)sequenceDiagram
participant W as with statement
participant M as context manager
participant B as block body
W->>M: __enter__()
M-->>W: value for "as"
W->>B: run the body
B-->>W: done, or an exception
W->>M: __exit__(exc_type, exc_value, traceback)
M-->>W: True suppresses the exception
__enter__ and __exit__ are dunder methods, like __iter__ and __next__ in module 10: you do not call them yourself; the with statement calls them. Module 20 lists all of them.
Just enough about classes
Section titled “Just enough about classes”You write a context manager as a class, as you wrote an iterator class in module 10. Module 18 teaches classes properly. For this module you need five facts:
class Timer:starts a class. Its indenteddefblocks are methods: functions that belong to the class.Timer()creates an instance: one object built from the class.__init__runs when you create the instance. It stores the starting data.- The first parameter of every method,
self, is the instance itself. Python passes it for you. self.elapsed = 0.0stores an attribute on the instance. Any method can read it later.
A context manager class: a timer
Section titled “A context manager class: a timer”A timer is the classic context manager: start the clock on entry, stop it on exit. time.perf_counter() returns a clock reading in seconds with high resolution. Only differences between two readings are meaningful.
import csvimport timefrom types import TracebackTypefrom typing import Self
class Timer: """Measure the time spent in a with block."""
def __init__(self) -> None: self.elapsed = 0.0
def __enter__(self) -> Self: self.start = time.perf_counter() return self
def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> None: self.elapsed = time.perf_counter() - self.start
with Timer() as t: with open("data/sales.csv", encoding="utf-8", newline="") as f: rows = list(csv.DictReader(f))print(f"Loaded {len(rows):,} rows in {t.elapsed:.3f}s")Loaded 20,228 rows in 0.026s__enter__ returns self, so t is the timer instance. Its hint Self (from typing) means “an instance of this class”, as in module 10. __exit__ stores the duration, and you read t.elapsed after the block. The duration differs on every machine and every run: this page masks it when it checks the output. __exit__ returns None, which is false, so any error inside the block continues after the clock stops. The hints on __exit__ are the standard ones; copy them as they are.
Exceptions inside a with block
Section titled “Exceptions inside a with block”__exit__ sees every exception that leaves the block. It can log it, clean up, and then decide: let the exception continue (return a false value) or swallow it (return True). The next class prints what __exit__ receives:
class ShowExit: def __enter__(self) -> Self: return self
def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> None: name = exc_type.__name__ if exc_type else None print(f"__exit__ got {name}: {exc_value}") # no return: None is a false value, so any exception continues
with ShowExit(): print(float("21.7"))with ShowExit(): print(float("error"))21.7__exit__ got None: None__exit__ got ValueError: could not convert string to float: 'error'ValueError: could not convert string to float: 'error'The first block ends normally, so all three arguments are None. The second block fails. __exit__ runs first, then the ValueError continues because __exit__ returned None, a false value. Annotate -> None for a manager that never suppresses, and -> bool for one that sometimes does. Return True only for errors you have really handled. Swallowing every error hides bugs. Example 5 uses this choice to undo a failed batch of rows.
contextlib.contextmanager: a context manager from a generator
Section titled “contextlib.contextmanager: a context manager from a generator”A class with two special methods is a lot of code for “do X, run the block, undo X”. The decorator contextlib.contextmanager builds a context manager from a generator function (module 10). The code before yield is the setup. The value you yield is what as receives. The code after yield is the cleanup.
from collections.abc import Iteratorfrom contextlib import contextmanagerfrom typing import Any
thresholds = {"max_quantity": 50, "max_discount": 0.2} # two of config.json
@contextmanagerdef temporary_setting( settings: dict[str, Any], key: str, value: Any) -> Iterator[dict[str, Any]]: old = settings[key] settings[key] = value try: yield settings finally: settings[key] = old
with temporary_setting(thresholds, "max_quantity", 1000) as current: print("inside:", current["max_quantity"])print("after:", thresholds["max_quantity"])with temporary_setting(thresholds, "max_discount", 0.5): print("inside:", thresholds["max_discount"]) print(thresholds["max_price"]) # no such keyinside: 1000after: 50inside: 0.5KeyError: 'max_price'An error inside the with block reappears at the yield line. The try/finally around yield restores the old value in both cases. Without it, the second block would leave max_discount at 0.5 for the rest of the program:
print(thresholds){'max_quantity': 50, 'max_discount': 0.2}The function returns Iterator[dict[str, Any]] because it is a generator that yields one dict. You could also write Generator[dict[str, Any], None, None].
The contextlib toolbox
Section titled “The contextlib toolbox”The module contextlib holds ready-made context managers. The worked examples use the first four.
| Tool | Does | Typical use |
|---|---|---|
suppress(FileNotFoundError) |
swallows the listed exceptions | skip an optional file, ignore a known harmless error |
redirect_stdout(buffer) |
sends print() output to another file object |
capture the output of a chatty library function |
chdir(path) |
changes the working directory and changes it back (Python 3.11+) | run a tool that writes into the current folder |
ExitStack() |
collects any number of context managers and closes them all | open a whole folder of files |
nullcontext(value) |
does nothing; as receives value |
make a context manager optional |
closing(thing) |
calls thing.close() at the end |
objects with close() but no with support |
redirect_stderr(buffer) |
like redirect_stdout, for error output |
capture warnings that a tool prints |
suppress replaces a try/except/pass with one readable line:
from contextlib import suppress
values = []for raw in ["21.7", "error", "22.1", "", "n/a", "21.9"]: with suppress(ValueError): values.append(float(raw))print(values)[21.7, 22.1, 21.9]Each failed float() call ends its own small with block. The loop continues with the next value.
Several context managers in one with
Section titled “Several context managers in one with”One with statement can manage several objects. Separate them with commas. Inside parentheses, you can put each one on its own line (Python 3.10+). They enter from left to right and exit in reverse order, like stacked decorators:
@contextmanagerdef stage(name: str) -> Iterator[None]: print(f"open {name}") try: yield finally: print(f"close {name}")
with ( stage("sales.csv"), stage("report.csv"),): print("copy rows")open sales.csvopen report.csvcopy rowsclose report.csvclose sales.csvThe last one opened is the first one closed. This order is safe: a later resource may depend on an earlier one, so it must be closed first. A real copy would read with open(src) as fin, open(dst, "w") as fout:.
Worked examples
Section titled “Worked examples”Example 1 — Time every step of a sales pipeline
Section titled “Example 1 — Time every step of a sales pipeline”Goal: A nightly job reads data/sales.csv, keeps the online orders and sums revenue by region. Add a @timed decorator that records each step’s duration in a dict, without touching the step code.
Step 1 — Write and run the plain steps
Section titled “Step 1 — Write and run the plain steps”def load_sales(path: str) -> list[dict[str, str]]: with open(path, encoding="utf-8", newline="") as f: return list(csv.DictReader(f))
def keep_online(rows: list[dict[str, str]]) -> list[dict[str, str]]: return [row for row in rows if row["channel"] == "online"]
def revenue_by_region(rows: list[dict[str, str]]) -> dict[str, float]: totals: dict[str, float] = {} for row in rows: totals[row["region"]] = totals.get(row["region"], 0.0) + float(row["revenue"]) return {region: round(total, 2) for region, total in sorted(totals.items())}
sales = load_sales("data/sales.csv")online = keep_online(sales)print(len(sales), len(online))print(revenue_by_region(online))20228 8495{'East': 426330.93, 'North': 377689.94, 'South': 383604.45, 'West': 331841.15}The three steps are plain functions with type hints. 8,495 of the 20,228 lines are online orders, as the data dictionary says. Get the logic right first. Add the instrumentation after.
Step 2 — Write the timing decorator
Section titled “Step 2 — Write the timing decorator”from collections.abc import Callable
TIMINGS: dict[str, float] = {}
def timed[**P, R](func: Callable[P, R]) -> Callable[P, R]: """Record the duration of the latest call of func in TIMINGS."""
@functools.wraps(func) def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: start = time.perf_counter() try: return func(*args, **kwargs) finally: TIMINGS[func.__name__] = time.perf_counter() - start
return wrapperThe finally clause records the time even when the step raises. Without it, a failing step would leave no trace in the report. The dict key is func.__name__, the name of the original step. functools.wraps makes the wrapper report that same name to everyone else.
Step 3 — Decorate the steps and rerun the pipeline
Section titled “Step 3 — Decorate the steps and rerun the pipeline”load_sales = timed(load_sales)keep_online = timed(keep_online)revenue_by_region = timed(revenue_by_region)
totals = revenue_by_region(keep_online(load_sales("data/sales.csv")))print(list(TIMINGS))print(all(seconds > 0 for seconds in TIMINGS.values()))print(totals["East"])['load_sales', 'keep_online', 'revenue_by_region']True426330.93load_sales = timed(load_sales) is what @timed does, written out, because the functions already exist. The dict keeps insertion order, so the keys list the steps in the order they ran. The result is the same as in Step 1: the decorator added timing and changed nothing else.
Step 4 — Print the timing report
Section titled “Step 4 — Print the timing report”for name, seconds in TIMINGS.items(): print(f"{name:<18} {seconds * 1000:7.1f} ms")slowest = max(TIMINGS, key=TIMINGS.__getitem__)print("slowest step:", slowest)load_sales 22.5 mskeep_online 1.3 msrevenue_by_region 1.2 msslowest step: load_salesReading and parsing 20,228 lines is far slower than filtering and summing them in memory. This is typical: input and output dominate small pipelines. The durations change from run to run; the ranking does not.
Step 5 — Check that the steps kept their identity
Section titled “Step 5 — Check that the steps kept their identity”print(load_sales.__name__, keep_online.__name__)print(load_sales.__wrapped__.__name__)print(inspect.signature(revenue_by_region))load_sales keep_onlineload_sales(rows: list[dict[str, str]]) -> dict[str, float]Thanks to functools.wraps, each step still reports its own name and signature. __wrapped__ gives you the undecorated step for a quick test.
Common mistakes:
- Measuring with
time.time(). It follows the wall clock, which can jump when the system adjusts the time. Usetime.perf_counter()for durations. - Recording the time after
return func(...). That line never runs. Usetry/finally, or store the result in a variable first. - Printing durations in an output that tests compare. Record them in a dict and print only what is stable, such as the step names or
seconds > 0.
Example 2 — Retry a flaky loader with backoff
Section titled “Example 2 — Retry a flaky loader with backoff”Goal: A loader fetches product data from an API that drops connections now and then. Retry the call with the waits from data/config.json, and test the retry logic without waiting for real.
Step 1 — Read the retry settings
Section titled “Step 1 — Read the retry settings”import json
with open("data/config.json", encoding="utf-8") as f: retry_config = json.load(f)["retry"]print(retry_config){'attempts': 3, 'backoff_seconds': [1, 2, 4]}attempts is the total number of calls, the first one included, as in module 06: 3 attempts are the first call plus at most 2 retries. Before retry k, the job waits backoff_seconds[k - 1]: 1 second, then 2. The third wait (4 seconds) is used only when someone raises attempts to 4. The waits double from one retry to the next. This pattern is exponential backoff (module 06): wait seconds before retry , here with . A growing wait gives a struggling server time to recover, and a fixed cap on the retries stops the loop. The errors worth retrying are transient errors: failures that may go away by themselves, such as a dropped connection or a timeout.
Step 2 — Build a fake flaky loader
Section titled “Step 2 — Build a fake flaky loader”from typing import Any
def make_flaky_fetch(failures: int) -> Callable[[str], dict[str, Any]]: """Return a fetch function whose first `failures` calls fail.""" calls = 0
def fetch_products(path: str) -> dict[str, Any]: nonlocal calls calls += 1 if calls <= failures: raise ConnectionError(f"call {calls}: connection reset by peer") with open(path, encoding="utf-8") as f: return json.load(f)
return fetch_products
fetch = make_flaky_fetch(failures=2)fetch("data/api/products_page_1.json")ConnectionError: call 1: connection reset by peerA real network fails at random, which makes a test useless. This fake, a stand-in that behaves like the real thing in a controlled way, fails exactly twice and then reads the saved API response data/api/products_page_1.json. The closure counts its calls with nonlocal, as in module 05.
Step 3 — Write the retry decorator factory
Section titled “Step 3 — Write the retry decorator factory”from collections.abc import Sequence
def retry[**P, R]( attempts: int, delays: Sequence[float], exceptions: tuple[type[Exception], ...] = (ConnectionError, TimeoutError), sleep: Callable[[float], None] = time.sleep,) -> Callable[[Callable[P, R]], Callable[P, R]]: """Call func up to `attempts` times; wait delays[k - 1] after failed call k.""" if len(delays) < attempts - 1: raise ValueError(f"{attempts} attempts need {attempts - 1} delays")
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 as exc: if attempt == attempts: raise # the last attempt failed: give up delay = delays[attempt - 1] print(f"{func.__name__} failed ({exc}); retry in {delay}s") sleep(delay) raise AssertionError("unreachable")
return wrapper
return decorateattempts is the total number of calls, first call included, as in module 06. The loop numbers the calls from 1. A success returns at once. A listed exception on call attempt waits delays[attempt - 1] and tries again. On the last call, the bare raise passes the error to the caller. So 3 attempts mean at most 3 calls and 2 waits; extra delays are not used. The check at the top rejects a config with too few delays at decoration time. The final raise AssertionError only tells a type checker that the loop cannot end without a return. except exceptions catches only the listed types: a ValueError from bad data is not transient, and retrying it would only waste time.
The sleep parameter is the key to testing. Production code uses the default time.sleep. A test passes a function that records the wait instead of waiting. Passing a dependency in as an argument, instead of hard-coding it, is called dependency injection.
Step 4 — Retry the flaky loader without waiting
Section titled “Step 4 — Retry the flaky loader without waiting”waits: list[float] = []
def fake_sleep(seconds: float) -> None: waits.append(seconds)
fetch = retry( retry_config["attempts"], retry_config["backoff_seconds"], sleep=fake_sleep)(make_flaky_fetch(failures=2))page = fetch("data/api/products_page_1.json")print(page["page"], len(page["data"]), page["data"][0]["name"])print("waits:", waits, "total:", sum(waits), "s")fetch_products failed (call 1: connection reset by peer); retry in 1sfetch_products failed (call 2: connection reset by peer); retry in 2s1 10 Wireless Earbudswaits: [1, 2] total: 3 sretry(...)(func) is the long form of @retry(...). The first two calls fail and the third, the last of the 3 attempts, returns the page with 10 products. The fake sleep recorded waits of 1 and 2 seconds, so the code would have waited 3 seconds in production, and the test took no time at all.
Step 5 — See the decorator give up
Section titled “Step 5 — See the decorator give up”waits.clear()
@retry(3, [0.5, 1.0], sleep=fake_sleep)def fetch_forecast(path: str) -> dict[str, Any]: raise TimeoutError("read timed out after 10s")
try: fetch_forecast("data/api/weather_forecast.json")finally: print("waits:", waits)fetch_forecast failed (read timed out after 10s); retry in 0.5sfetch_forecast failed (read timed out after 10s); retry in 1.0swaits: [0.5, 1.0]TimeoutError: read timed out after 10sHere the @ form takes the arguments directly. The function always fails, so the decorator tries 3 times, waits twice and then lets the last TimeoutError reach the caller. Giving up is a feature: a pipeline that retries forever hides an outage instead of reporting it.
Common mistakes:
- Retrying every exception with
except Exception. AKeyErrororValueErroris a bug or bad data. It fails the same way every time. - Retrying without a limit, or without a wait. A tight retry loop can flood a server that is already overloaded.
- Calling
time.sleep()inside a test. Inject the sleep function and record the waits. - Retrying an action that is not idempotent (safe to repeat with the same effect), such as “charge the customer”. A retry after a lost response can charge twice.
Example 3 — Cache an expensive customer lookup
Section titled “Example 3 — Cache an expensive customer lookup”Goal: A dashboard shows the lifetime revenue of five customers and refreshes 20 times. Each lookup scans all 20,228 sales lines. Cache the results so each customer is scanned once.
Step 1 — Write the slow lookup and count the scans
Section titled “Step 1 — Write the slow lookup and count the scans”scan_log: list[str] = []
def customer_revenue(customer_id: str) -> float: scan_log.append(customer_id) total = sum(float(r["revenue"]) for r in sales if r["customer_id"] == customer_id) return round(total, 2)
dashboard = ["C00618", "C00971", "C01204", "C00040", "C02503"]for _ in range(20): values = [customer_revenue(cid) for cid in dashboard]print(values)print("scans:", len(scan_log))[4431.1, 352.93, 712.86, 2702.38, 327.99]scans: 100Every refresh scans the whole file again for every customer: 100 scans for 5 distinct answers. scan_log makes the waste visible without timing anything.
Step 2 — Write a memoizing decorator
Section titled “Step 2 — Write a memoizing decorator”def memoize(func: Callable[[str], float]) -> Callable[[str], float]: cache: dict[str, float] = {}
@functools.wraps(func) def wrapper(key: str) -> float: if key not in cache: cache[key] = func(key) return cache[key]
return wrapper
scan_log.clear()cached_revenue = memoize(customer_revenue)for _ in range(20): values = [cached_revenue(cid) for cid in dashboard]print(values)print("scans:", len(scan_log))[4431.1, 352.93, 712.86, 2702.38, 327.99]scans: 5Memoization (module 09) stores the result of a function call by its arguments and returns the stored result when the same arguments come again. The dict cache lives in the closure. The first refresh fills it with 5 results. The other 19 refreshes only read it. The values are identical; the work dropped from 100 scans to 5.
Step 3 — Use functools.lru_cache instead
Section titled “Step 3 — Use functools.lru_cache instead”scan_log.clear()lru_revenue = functools.lru_cache(maxsize=256)(customer_revenue)for _ in range(20): values = [lru_revenue(cid) for cid in dashboard]print("scans:", len(scan_log))print(lru_revenue.cache_info())scans: 5CacheInfo(hits=95, misses=5, maxsize=256, currsize=5)functools.lru_cache, which you used in module 09, does the same job and handles any number of hashable arguments. A cache hit is a call answered from the cache; a cache miss is a call that runs the function. Here 5 misses fill the cache and 95 hits read it. LRU means “least recently used”: when the cache holds maxsize results, it drops the one that was used longest ago. Use @functools.cache (no size limit) when the set of possible arguments is small.
Step 4 — Clear the cache when the data changes
Section titled “Step 4 — Clear the cache when the data changes”sales.append({"customer_id": "C02503", "revenue": "79.99"}) # a new order arrivesprint(lru_revenue("C02503"))lru_revenue.cache_clear()print(lru_revenue("C02503"))sales.pop() # remove the demo order againlru_revenue.cache_clear()327.99407.98The cache does not know that sales changed, so the first call returns the stale 327.99. cache_clear() empties the cache, and the next call scans the updated data. A cache is safe only while the data behind it stays the same. Clear it, or give the cache a time limit, when the data can change.
Step 5 — See which arguments a cache accepts
Section titled “Step 5 — See which arguments a cache accepts”print(lru_revenue("C00618"))print(lru_revenue(["C00618"]))4431.1TypeError: unhashable type: 'list'The cache stores its results in a dict, so the arguments become a dict key and must be hashable (module 04). A string works. A list fails before the function even runs. Pass a tuple instead of a list, or cache a function of the ids one at a time.
Common mistakes:
- Caching a function with side effects, such as one that writes a file or sends an email. The second call returns the stored result and skips the side effect.
- Caching a function that returns a list or dict, then changing the returned object. Every later caller gets the changed object. Return tuples or copies.
- Forgetting that the cache keeps every result alive.
@cacheon a function that sees millions of different arguments grows without limit; uselru_cache(maxsize=...).
Example 4 — Validate the input of a pipeline step
Section titled “Example 4 — Validate the input of a pipeline step”Goal: Pipeline steps receive a table as a dict of columns, like the data a DataFrame holds. Reject a table that lacks a required column, and reject a discount rate above the max_discount of 0.2 in data/config.json.
Step 1 — Build a small column table
Section titled “Step 1 — Build a small column table”order_lines = sales[12:17] # five lines from January 2023table: dict[str, list[Any]] = { "order_id": [r["order_id"] for r in order_lines], "unit_price": [float(r["unit_price"]) for r in order_lines], "quantity": [int(r["quantity"]) for r in order_lines],}for name, column in table.items(): print(f"{name:<11}", column)order_id ['O000010', 'O000010', 'O000011', 'O000011', 'O000012']unit_price [16.99, 34.99, 69.99, 34.99, 189.99]quantity [2, 1, 1, 3, 5]A dict of equal-length lists is a columnar table: one list per column instead of one dict per row. pandas stores a DataFrame this way (module 24). Orders O000010 and O000011 have two lines each, so their ids appear twice.
Step 2 — Write a decorator that checks the columns
Section titled “Step 2 — Write a decorator that checks the columns”type Table = dict[str, list[Any]]
def require_columns[**P, R](*names: str) -> Callable[[Callable[P, R]], Callable[P, R]]: """Check that the first argument is a table with the given columns."""
def decorate(func: Callable[P, R]) -> Callable[P, R]: @functools.wraps(func) def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: data = args[0] if not isinstance(data, dict): raise TypeError(f"{func.__name__} expects a dict of columns") missing = [name for name in names if name not in data] if missing: raise ValueError(f"{func.__name__} needs columns {missing}") lengths = {len(column) for column in data.values()} if len(lengths) > 1: raise ValueError(f"{func.__name__}: columns differ in length") return func(*args, **kwargs)
return wrapper
return decorateThe line type Table = dict[str, list[Any]] is a type alias (Python 3.12, module 10): a short name for a long type. The wrapper checks three rules before the step runs: the first argument is a dict, every required column exists, and all columns have the same length. The isinstance() check also tells a type checker that data is a dict from then on. A failure raises ValueError with the step’s name, so the error message points to the right place in a long pipeline.
Step 3 — Decorate a step and run it on good data
Section titled “Step 3 — Decorate a step and run it on good data”@require_columns("unit_price", "quantity")def add_line_total(data: Table) -> Table: totals = [p * q for p, q in zip(data["unit_price"], data["quantity"])] return {**data, "line_total": totals}
result = add_line_total(table)print(result["line_total"])[33.98, 34.99, 69.99, 104.97, 949.95]The check passes, so the step runs and returns a new table with one more column. {**data, "line_total": totals} copies the input dict and adds a key, so the input table stays unchanged.
Step 4 — Feed it a broken table
Section titled “Step 4 — Feed it a broken table”broken = {"order_id": ["O000001"], "unit_price": [69.99]}add_line_total(broken)ValueError: add_line_total needs columns ['quantity']Without the decorator, the step would fail deep inside with KeyError: 'quantity'. The decorator fails early, with a message that names the step and every missing column. Failing early with a clear message is called fail fast.
Step 5 — Validate named arguments with inspect.signature
Section titled “Step 5 — Validate named arguments with inspect.signature”def check_args(**rules: Callable[[Any], bool]): """Check named arguments, e.g. check_args(rate=lambda r: 0 <= r <= 0.2)."""
def decorate(func): signature = inspect.signature(func)
@functools.wraps(func) def wrapper(*args, **kwargs): bound = signature.bind(*args, **kwargs) bound.apply_defaults() for name, rule in rules.items(): value = bound.arguments[name] if not rule(value): raise ValueError(f"{func.__name__}: invalid {name}={value!r}") return func(*args, **kwargs)
return wrapper
return decorate
@check_args(rate=lambda r: 0 <= r <= 0.2)def apply_discount(data: Table, rate: float = 0.0) -> list[float]: return [round(p * (1 - rate), 2) for p in data["unit_price"]]
print(apply_discount(table, 0.1))print(apply_discount(table, rate=0.05))print(apply_discount(table, rate=0.5))[15.29, 31.49, 62.99, 31.49, 170.99][16.14, 33.24, 66.49, 33.24, 180.49]ValueError: apply_discount: invalid rate=0.5signature.bind(*args, **kwargs) matches the call’s arguments to the parameter names, exactly as Python would. So the rule finds rate whether the caller passed it by position (0.1) or by keyword. apply_defaults() fills in parameters the caller left out, so a rule also checks a default value. This decorator leaves out the [**P, R] hints to keep the focus on bind(). Add them as in Step 2 when you use it in real code.
Common mistakes:
- Reading
args[0]inrequire_columnsand calling the step by keyword:add_line_total(data=table)puts the table inkwargs, andargs[0]raisesIndexError. Make the table parameter positional-only (def add_line_total(data: Table, /)), or bind the arguments as in Step 5. - Reading
kwargs["rate"]directly. A positional call puts the value inargs, and the check silently does nothing. Bind the arguments to the signature. - Validating with
assert. Python skips everyassertwhen it runs with the-Oflag. RaiseValueErrororTypeErrorfor bad input. - Repeating the same checks at the top of ten steps. That is exactly the duplication a decorator removes.
Example 5 — Load readings in all-or-nothing batches
Section titled “Example 5 — Load readings in all-or-nothing batches”Goal: A loader appends temperature readings from data/readings.txt to a list in batches of 10 lines. A batch with a bad line must leave no partial rows behind. Write a context manager class that undoes a failed batch.
Step 1 — Read the lines and cut them into batches
Section titled “Step 1 — Read the lines and cut them into batches”with open("data/readings.txt", encoding="utf-8") as f: lines = f.read().splitlines()batches = [lines[i : i + 10] for i in range(0, len(lines), 10)]print(len(lines), [len(batch) for batch in batches])print(batches[1][:3])43 [10, 10, 10, 10, 3]['22.7', 'error', '22.4']The file has 43 lines, so the last batch has 3. Line 12 holds error; it is the second line of the second batch. Lines 24 and 35 are broken too.
Step 2 — Write the context manager class
Section titled “Step 2 — Write the context manager class”class Staging: """Append to a list inside a with block; undo the appends on error."""
def __init__( self, target: list[float], skip: tuple[type[Exception], ...] = () ) -> None: self.target = target self.skip = skip self.rolled_back = 0
def __enter__(self) -> list[float]: self.start = len(self.target) return self.target
def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> bool: if exc_type is None: return False added = len(self.target) - self.start del self.target[self.start :] self.rolled_back += 1 print(f"rollback ({exc_type.__name__}: {exc_value}): removed {added} row(s)") return issubclass(exc_type, self.skip)__enter__ remembers the length of the list and returns the list itself, so the block appends to it through the as name. On an error, __exit__ deletes everything added since then. This undo is a rollback, a word from databases. Its return value decides what happens next: True only when the exception type is in skip. issubclass(exc_type, ()) is False, so by default every error continues.
Step 3 — Load a good batch
Section titled “Step 3 — Load a good batch”readings: list[float] = []with Staging(readings) as staged: for raw in batches[0]: staged.append(float(raw))print(len(readings), readings[:3])10 [21.0, 21.9, 21.4]The block ended without an error. __exit__ received three None values and returned False, and the 10 rows stayed.
Step 4 — Load a batch with a bad line
Section titled “Step 4 — Load a batch with a bad line”try: with Staging(readings) as staged: for raw in batches[1]: staged.append(float(raw))finally: print("rows kept:", len(readings))rollback (ValueError: could not convert string to float: 'error'): removed 1 row(s)rows kept: 10ValueError: could not convert string to float: 'error'Line 11 (22.7) was appended, then line 12 failed. __exit__ removed the one new row and returned False, so the ValueError continued to the caller. The list holds exactly the 10 rows of the good batch. A loader is now atomic: a batch is applied completely or not at all.
Step 5 — Skip bad batches and carry on
Section titled “Step 5 — Skip bad batches and carry on”readings.clear()staging = Staging(readings, skip=(ValueError,))for batch in batches: with staging as staged: for raw in batch: staged.append(float(raw))print("batches rolled back:", staging.rolled_back)print("rows kept:", len(readings))rollback (ValueError: could not convert string to float: 'error'): removed 1 row(s)rollback (ValueError: could not convert string to float: ''): removed 3 row(s)rollback (ValueError: could not convert string to float: 'n/a'): removed 4 row(s)batches rolled back: 3rows kept: 13With skip=(ValueError,), __exit__ returns True for a ValueError, so the loop goes on with the next batch. Three batches contain a bad line and are rolled back; batches 1 and 5 keep their 10 + 3 rows. One instance serves all five with blocks because __enter__ records a new start each time. Whether to skip or stop is a business decision: skipping keeps the pipeline running, stopping makes the problem impossible to miss.
Common mistakes:
- Returning
Truefrom__exit__for every exception. AKeyErrorfrom a typo in your code would vanish without a trace. Suppress only the types you expect. - Forgetting
return self(or another value) in__enter__. Thenas stagedbindsNone, and the firststaged.appendraisesAttributeError. - Doing the cleanup in
__exit__only when there is no error. Cleanup that must always happen, such as closing a file, goes before anyif.
Example 6 — Write a report in a temporary folder and capture output
Section titled “Example 6 — Write a report in a temporary folder and capture output”Goal: A report tool writes its CSV into the current working directory, and a legacy training function prints a line per epoch. Run the tool in a throwaway folder, and capture the training log as a string.
Step 1 — Write a working-directory context manager
Section titled “Step 1 — Write a working-directory context manager”import osfrom pathlib import Path
@contextmanagerdef working_directory(path: str | Path) -> Iterator[Path]: """Change into path for the with block, then change back.""" previous = Path.cwd() os.chdir(path) try: yield Path.cwd() finally: os.chdir(previous)Path.cwd() returns the current working directory and os.chdir() changes it. The finally clause changes back even when the block fails. The yielded value is the new folder, for the as name.
Step 2 — Run the report tool in a temporary folder
Section titled “Step 2 — Run the report tool in a temporary folder”import tempfile
def write_region_report(totals: dict[str, float]) -> None: """A tool that always writes region_report.csv into the current folder.""" with open("region_report.csv", "w", encoding="utf-8", newline="") as f: writer = csv.writer(f) writer.writerow(["region", "online_revenue"]) writer.writerows(totals.items())
start = Path.cwd()with tempfile.TemporaryDirectory() as tmp, working_directory(tmp): write_region_report(totals) print(os.listdir(".")) print(Path("region_report.csv").read_text(encoding="utf-8"), end="")print(Path.cwd() == start, Path("region_report.csv").exists())['region_report.csv']region,online_revenueEast,426330.93North,377689.94South,383604.45West,331841.15True Falsetempfile.TemporaryDirectory() is itself a context manager: it creates an empty folder and deletes it, with its contents, at the end of the block. The two managers enter in order, so the folder exists before working_directory changes into it, and they exit in reverse. Afterwards you are back in the project folder, and no stray report file is left in it.
Step 3 — Check that an error still restores the folder
Section titled “Step 3 — Check that an error still restores the folder”with suppress(RuntimeError): with tempfile.TemporaryDirectory() as tmp, working_directory(tmp): raise RuntimeError("report tool crashed")print(Path.cwd() == start)TrueThe block crashed, both managers cleaned up, and suppress swallowed the error so that the page can continue. A working-directory change that leaks after an error makes every later relative path, such as data/sales.csv, point to the wrong place.
Step 4 — Use contextlib.chdir from the standard library
Section titled “Step 4 — Use contextlib.chdir from the standard library”from contextlib import chdir
with tempfile.TemporaryDirectory() as tmp, chdir(tmp): write_region_report(totals) print(sorted(os.listdir(".")))print(Path.cwd() == start)['region_report.csv']TrueSince Python 3.11, contextlib.chdir does exactly what working_directory does. Use the standard tool in real code. Writing your own once shows you that there is no magic inside.
Step 5 — Capture a chatty function with redirect_stdout
Section titled “Step 5 — Capture a chatty function with redirect_stdout”import iofrom contextlib import redirect_stdout
def fit_slope(xs: list[float], ys: list[float], epochs: int = 30) -> float: """Fit y = w * x by gradient descent; print the loss every epoch.""" w = 0.0 for epoch in range(1, epochs + 1): grad = sum(2 * (w * x - y) * x for x, y in zip(xs, ys)) / len(xs) w -= 0.05 * grad loss = sum((w * x - y) ** 2 for x, y in zip(xs, ys)) / len(xs) print(f"epoch {epoch:2d} loss {loss:.4f}") return w
buffer = io.StringIO()with redirect_stdout(buffer): w = fit_slope([1.0, 2.0, 3.0, 4.0], [2.1, 3.9, 6.2, 7.8])log_lines = buffer.getvalue().splitlines()print(len(log_lines), "lines captured")print(log_lines[0])print(log_lines[-1])print(round(w, 3))30 lines capturedepoch 1 loss 1.8805epoch 30 loss 0.02431.99io.StringIO() is a file object that keeps its text in memory. Inside the block, every print() writes to it instead of the terminal. The 30 log lines are now data: you can keep the last one, save them to a file or search them. fit_slope uses the gradient descent idea from module 03 to fit a line through the four points, and finds a slope close to 2.
Common mistakes:
- Calling
os.chdir()without a way back. Every relative path after it breaks. Usecontextlib.chdir, which always restores the folder. - Writing temporary files into the project folder and deleting them by hand. Use
tempfile.TemporaryDirectory(); it cleans up even after an error. - Expecting
redirect_stdoutto capture output from C extensions or subprocesses. It replaces only Python’ssys.stdout. For a subprocess, usesubprocess.run(..., capture_output=True)(module 09).
Example 7 — Open a folder of monthly reports with ExitStack
Section titled “Example 7 — Open a folder of monthly reports with ExitStack”Goal: Read the six monthly extracts in data/reports/ at the same time, find the file with a different column order and total the revenue of each file. The number of files is known only at run time.
Step 1 — List the files
Section titled “Step 1 — List the files”paths = sorted(Path("data/reports").glob("*.csv"))print([p.name for p in paths])['2024-01.csv', '2024-02.csv', '2024-03.csv', '2024-04.csv', '2024-05.csv', '2024-06.csv']A with statement with commas needs the files written out in the code. Here the list comes from the folder, so next month it may hold seven files.
Step 2 — Open every file with an ExitStack
Section titled “Step 2 — Open every file with an ExitStack”from contextlib import ExitStack
with ExitStack() as stack: files = [ stack.enter_context(open(p, encoding="utf-8", newline="")) for p in paths ] stack.callback(print, f"closing {len(files)} report files") readers = [csv.DictReader(f) for f in files] headers = [tuple(reader.fieldnames) for reader in readers] standard = headers[0] for path, header in zip(paths, headers): if header != standard: print("different column order:", path.name) month_totals = { p.stem: round(sum(float(row["revenue"]) for row in reader), 2) for p, reader in zip(paths, readers) }print(all(f.closed for f in files))different column order: 2024-04.csvclosing 6 report filesTrueAn ExitStack is a context manager that holds other context managers. stack.enter_context(cm) enters cm and returns its as value; here, an open file. stack.callback(func, *args) registers a plain function to call at the end. When the with ExitStack() block ends, the stack exits everything in reverse order: first the callback prints, then the six files close. If opening the fourth file had failed, the stack would still close the first three.
Step 3 — Read the totals
Section titled “Step 3 — Read the totals”for month, total in month_totals.items(): print(f"{month} {total:>10,.2f}")print(f"total {sum(month_totals.values()):>10,.2f}")2024-01 14,162.332024-02 4,719.042024-03 12,296.722024-04 10,879.042024-05 6,675.862024-06 8,533.40total 57,266.39csv.DictReader reads each column by its name, so the different column order of 2024-04.csv does no harm. The totals match the data dictionary.
Step 4 — Read an optional file with suppress
Section titled “Step 4 — Read an optional file with suppress”adjustments = 0.0with suppress(FileNotFoundError): text = Path("data/reports/adjustments.txt").read_text(encoding="utf-8") adjustments = float(text)print("adjustments:", adjustments)adjustments: 0.0Some months have a manual adjustments file and most do not. suppress(FileNotFoundError) skips the rest of the block when the file is missing, and the default stays. It does not hide a broken file: a ValueError from bad content still stops the program.
Common mistakes:
- Opening files in a loop without
with, collecting them in a list and forgetting to close them on error.ExitStackcloses every file that was opened, even when a later one fails. - Joining CSV files line by line.
2024-04.csvhas its columns in a different order, so its numbers land in the wrong columns. Read rows by column name. - Wrapping a large block in
suppress(Exception). It hides every bug in the block. Suppress one specific exception around the one line that can raise it.
Example 8 — Stack a timer and a retry in the right order
Section titled “Example 8 — Stack a timer and a retry in the right order”Goal: A loader has both a timer and a retry. Decide which goes on top: should the time include the failed attempts and the waits, or only the final attempt?
Step 1 — Build a timer that logs every call
Section titled “Step 1 — Build a timer that logs every call”CALL_LOG: list[str] = []
def logged_timer[**P, R](func: Callable[P, R]) -> Callable[P, R]: @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 CALL_LOG.append(f"{func.__name__}: {elapsed >= 0}")
return wrapperThis timer appends one entry per call, so the length of CALL_LOG counts how often the timer ran. The entry stores elapsed >= 0 instead of the duration, to keep the output stable.
Step 2 — Put the timer on top
Section titled “Step 2 — Put the timer on top”waits.clear()CALL_LOG.clear()fetch_once = logged_timer( retry(3, [1, 2], sleep=fake_sleep)(make_flaky_fetch(failures=2)))page = fetch_once("data/api/products_page_2.json")print(page["page"], "timer entries:", len(CALL_LOG))fetch_products failed (call 1: connection reset by peer); retry in 1sfetch_products failed (call 2: connection reset by peer); retry in 2s2 timer entries: 1This is the same as @logged_timer above @retry(3, [1, 2], ...). The timer wraps the retry, so it runs once and its duration covers all three attempts and both waits. That is the number a user feels: “loading page 2 took 3 seconds”.
Step 3 — Put the retry on top
Section titled “Step 3 — Put the retry on top”waits.clear()CALL_LOG.clear()fetch_each = retry(3, [1, 2], sleep=fake_sleep)( logged_timer(make_flaky_fetch(failures=2)))page = fetch_each("data/api/products_page_2.json")print(page["page"], "timer entries:", len(CALL_LOG))print(CALL_LOG)fetch_products failed (call 1: connection reset by peer); retry in 1sfetch_products failed (call 2: connection reset by peer); retry in 2s2 timer entries: 3['fetch_products: True', 'fetch_products: True', 'fetch_products: True']Now the retry wraps the timer, so each attempt is timed on its own: 3 entries, and no wait is included. That is the number an engineer needs to see whether each attempt is slow. The finally in the timer recorded the two failed attempts too.
Step 4 — Read the stack from the function’s metadata
Section titled “Step 4 — Read the stack from the function’s metadata”print(fetch_each.__name__)print(fetch_each.__wrapped__.__name__)print(fetch_each.__wrapped__.__wrapped__.__name__)fetch_productsfetch_productsfetch_productsEach layer copied the name with functools.wraps, so all three layers report fetch_products. Each __wrapped__ peels one layer off. inspect.unwrap(fetch_each) peels them all.
Common mistakes:
- Reading a decorator stack top-down as “first this, then that” at decoration time. The bottom decorator is applied first; the top one runs first at call time.
- Putting
@functools.cacheabove@timed. Cache hits never reach the timer, so the timings show only the misses. Decide which one you want to see. - Putting an audit log or a call counter below a cache. Cache hits never reach it, so the log misses every repeated call. A pure argument check below a cache is safe: a cached call already passed the check once, and a failed check raises, so it is never cached.
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
No functools.wraps in the wrapper |
Every decorated function is named wrapper; docstrings and signatures disappear |
Add @functools.wraps(func) to every wrapper |
No return in the wrapper |
The decorated function returns None |
return func(*args, **kwargs) |
@factory without parentheses |
TypeError or a strange object at the first call |
Write @factory() or @factory(arg) |
Calling the function in the decorator: @log(func()) |
The function runs once at decoration time | Pass the function object, without () |
Wrapper with fixed parameters def wrapper(x) |
TypeError when the function has other parameters |
Use *args, **kwargs and forward both |
Hints Callable[..., Any] on a decorator |
The type checker misses wrong arguments | Use def deco[**P, R](func: Callable[P, R]) -> Callable[P, R] |
Retrying except Exception |
Bugs and bad data are retried and slow everything down | Retry only transient errors such as ConnectionError, TimeoutError |
| Caching a function of data that changes | Stale results | Call cache_clear(), or do not cache |
| A list argument to a cached function | TypeError: unhashable type: 'list' |
Pass a tuple |
__enter__ without return self |
AttributeError: 'NoneType' object has no attribute ... |
Return the object for as |
__exit__ that returns True always |
Errors vanish silently | Return True only for exception types you handle |
@contextmanager without try/finally |
Cleanup is skipped when the block raises | Put yield inside try/finally |
os.chdir() without changing back |
Relative paths such as data/sales.csv fail later |
with contextlib.chdir(path): |
suppress(Exception) around a large block |
Bugs disappear | Suppress one exception type around one line |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Web development: Flask and FastAPI register URL handlers with decorators (
@app.get("/orders")), and check logins with decorators such as@login_required. Database sessions are context managers that commit on success and roll back on error. - Automation: deployment and backup scripts wrap network calls in retry decorators with backoff, and use
tempfile.TemporaryDirectory()andcontextlib.chdirto build files in a clean folder. - Tooling: pytest is built on decorators (
@pytest.fixture,@pytest.mark.parametrize) and context managers (with pytest.raises(ValueError):). Command-line libraries register sub-commands with decorators. - Concurrency and systems: locks (
with lock:), thread pools (with ThreadPoolExecutor() as pool:, module 15) and network connections all release their resource through__exit__.
Summary
Section titled “Summary”- A function is an object with metadata such as
__name__and__doc__. You can store it, pass it and return it. - A decorator takes a function and returns a replacement.
@decoabovedef fmeansf = deco(f). It runs once at decoration time; its wrapper runs at every call. - A wrapper accepts
*args, **kwargs, forwards them and returns the result.@functools.wraps(func)keeps the name, docstring and signature, and adds__wrapped__. - A decorator with arguments is a factory with three levels: settings, function, call.
- Type a decorator with
def deco[**P, R](func: Callable[P, R]) -> Callable[P, R]so that type checkers still see the real signature. - Pipeline decorators: timing with
perf_counterandfinally; retry with a limit, exponential backoff and an injectedsleep; caching withlru_cacheand hashable arguments; validation that fails fast with a clear message. - Stacked decorators apply bottom-up and run top-down. The order changes what a timer measures and what a cache skips.
- A context manager has
__enter__(its return value goes toas) and__exit__(always runs; a true return value suppresses the exception). @contextmanagerturns a generator into a context manager: setup,yieldinsidetry, cleanup infinally.contextlibgives yousuppress,redirect_stdout,chdir,ExitStack,nullcontextandclosing. Several managers in onewithexit in reverse order.
Self-check questions
Section titled “Self-check questions”Q1. What does @log_calls above def load(): do, written without the @?
Answer
load = log_calls(load). Python defines the function, passes it to log_calls and binds the name load to whatever log_calls returns, usually a wrapper.
Q2. A decorator prints "registered" in its body, outside the wrapper. When does that line run?
Answer
Once, at decoration time: when Python executes the def statement, usually at import. It does not run at each call. Only the code inside the wrapper runs at call time.
Q3. A wrapper is def wrapper(*args, **kwargs): func(*args, **kwargs). What does the decorated function return?
Answer
Always None. The wrapper calls func but throws its result away. Write return func(*args, **kwargs).
Q4. Name two things that break when a decorator does not use functools.wraps.
Answer
Any two of: __name__ becomes 'wrapper', so logs, reports and registries show the wrong name; __doc__ becomes None, so help() shows nothing; inspect.signature() shows (*args, **kwargs); there is no __wrapped__ to reach the original function in tests.
Q5. Why does a decorator with arguments, such as @retry(3, [1, 2, 4]), need three nested functions?
Answer
Python first calls retry(3, [1, 2, 4]), so the outer function takes the settings and must return a decorator. That decorator takes the function and returns the wrapper. The wrapper takes the call’s arguments. Settings, function and call arrive at three different moments.
Q6. In this stack, which decorator runs first when you call load()?
@timed@retry(3, [1, 2])def load(): ...Answer
timed. It is the outermost layer: load = timed(retry(3, [1, 2])(load)). Its wrapper starts the clock, then calls the retry wrapper, which calls the original. So the time includes every attempt and every wait.
Q7. Why should a retry decorator take a sleep parameter instead of calling time.sleep() directly?
Answer
So that tests can pass a fake function that records the waits instead of waiting. The test checks the backoff schedule ([1, 2]) and runs in no time. Production code keeps the default time.sleep. This is dependency injection.
Q8. Why does lru_cache raise TypeError: unhashable type: 'list' for a list argument?
Answer
The cache stores results in a dict keyed by the arguments. Dict keys must be hashable, and a list is mutable, so it is not hashable. Pass a tuple instead.
Q9. What are the three arguments of __exit__, and what does its return value mean?
Answer
exc_type, exc_value and traceback: the type, the exception object and its traceback, or three None values when the block ended normally. A true return value suppresses the exception; a false value (including None) lets it continue.
Q10. What is wrong with this context manager?
@contextmanagerdef temporary_setting(settings, key, value): old = settings[key] settings[key] = value yield settings settings[key] = oldAnswer
The yield is not inside try/finally. When the with block raises, the exception reappears at the yield, and the line that restores the old value never runs. Write try: yield settings and finally: settings[key] = old.
Q11. When do you need ExitStack instead of a with statement with commas?
Answer
When the number of context managers is known only at run time, for example all CSV files in a folder. A comma-separated with lists a fixed set in the code. ExitStack enters each one with enter_context() and exits all of them, in reverse order, even if a later one fails to open.
Q12. Two context managers are in one with: with A() as a, B() as b:. In which order do their __exit__ methods run?
Answer
B first, then A: reverse order of entry. The last resource opened is the first one closed, because it may depend on the earlier ones.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Exercises: 28 exercises with hints and full solutions, from warm-up to challenge.
- Mini-project: instrument a sales pipeline with step, retry, validation and run-tracking tools.
- Cheat sheet: decorator and context manager templates,
functoolsandcontextlibon one page. - Next module: 12. Type hints teaches built-in generics,
X | None,Callable,TypedDict,Protocoland type checking with mypy.