Skip to content

11. Decorators and context managers — Mini-project

A nightly job turns data/sales.csv into two small reports: revenue by region and the top three store cities. The job works, but nobody can see inside it. Last week it failed twice because the network drive with the sales file was not ready, and once because an upstream change dropped a column. Each time, the only clue was a bare traceback.

Your task: add the instrumentation without rewriting the business logic. Every step must report its name and its row count. A flaky file source must be retried with the backoff from the config. Bad input must fail early with a clear message. Each run must end with a one-line status, success or failure. And the job must not leave files behind in the project folder while you test it.

The project uses every part of module 11: decorators without and with arguments, functools.wraps, the retry, caching and validation patterns, the order of stacked decorators, a context manager class with exception handling in __exit__, and contextlib.chdir with a temporary folder.

  • data/sales.csv: 20,228 order lines, 2023–2024. The job uses five columns: store_id, region, quantity, discount and revenue.
  • data/stores.csv: 12 stores, with store_id and city.
  • data/config.json: retry.attempts is 3 and retry.backoff_seconds is [1, 2, 4]. As in module 06, attempts is the total number of calls, the first one included: at most 3 calls and 2 waits (1 and 2 seconds); the 4-second wait is spare; thresholds holds min_quantity 1, max_quantity 50 and max_discount 0.2.

The data dictionary gives the revenue by region for checking: East 993,684, South 891,766, North 888,229 and West 822,845 (rounded to whole USD).

To make the failures repeatable, you simulate the network drive with a fake open function whose first two calls raise ConnectionError.

Your script must:

  1. Store each table as a dict of columns (type Table = dict[str, list[Any]]).
  2. Provide a @step decorator that appends (name, rows, seconds) to a step log after each successful call. Use functools.wraps and the [**P] type parameter.
  3. Provide a @retry(attempts, delays, sleep=...) decorator factory that makes at most attempts calls, retries only ConnectionError and TimeoutError, waits delays[k - 1] before retry k, re-raises the error of the last attempt, and accepts a fake sleep. Take attempts and delays from config.json.
  4. Provide a @require_columns(*names) decorator factory that raises ValueError naming the step and the missing columns.
  5. Cache the store-to-city lookup with functools.cache, and report the cache statistics.
  6. Provide a context manager class PipelineRun that clears the step log on entry, prints the step log and a status line on exit, stores the status in an attribute, and never suppresses an exception.
  7. Run five steps: load_sales (retried), clean (thresholds), add_city, revenue_by_region and top_cities. Stack the decorators so that the logged duration of load_sales covers all its attempts and waits, not only the last attempt.
  8. Write output/region_report.csv and output/top_cities.csv inside a temporary folder, with contextlib.chdir.
  9. Run the job a second time on a table without a discount column, and show the failed status and the error message.
  10. End with assert checks: the region totals, the waits [1, 2], the cache misses and the failed status.

The main run prints exactly this:

Expected output
run nightly-2024-12-31: started
load_sales failed (network drive not ready, call 1); retry in 1s
load_sales failed (network drive not ready, call 2); retry in 2s
load_sales 20228 rows
clean 20228 rows
add_city 20228 rows
revenue_by_region 4 rows
top_cities 3 rows
run nightly-2024-12-31: success
  1. Start with plain functions. Write load_sales, clean, add_city, revenue_by_region and top_cities without decorators, and check their results on the real file.

  2. Write @step. Time the call with time.perf_counter(). Count the rows as the length of the first column of the returned table. Append to a module-level list STEP_LOG.

  3. Write @retry. Copy the structure of the lesson’s Example 2. Pass sleep=WAITS.append in the project, so that the waits are recorded, not slept.

  4. Write the fake file source. A closure counts its calls and raises ConnectionError on the first two. After that, it calls the real open(). load_sales takes the opener as a parameter with the default open.

  5. Choose the stacking order. @step must sit above @retry, so that its duration covers all attempts and waits. Write down why before you run it.

  6. Write @require_columns and put it below @step on every step that reads columns.

  7. Write PipelineRun. __enter__ clears STEP_LOG and prints the start line. __exit__ prints the log and the status, and returns None.

  8. Run and report. Run the five steps in a with PipelineRun(...) block. Print the two report tables, the waits and the cache statistics.

  9. Write the files in with tempfile.TemporaryDirectory() as folder, chdir(folder):, and list the folder’s contents.

  10. Break it on purpose. Remove the discount column from the loaded table and run clean in a second PipelineRun. Catch the ValueError outside the with block.

A skeleton to start from:

nightly_job.py (starter)
import csv
import functools
import json
import tempfile
import time
from collections.abc import Callable, Sequence
from contextlib import chdir
from pathlib import Path
from typing import Any
type Table = dict[str, list[Any]]
CONFIG = json.loads(Path("data/config.json").read_text(encoding="utf-8"))
STEP_LOG: list[tuple[str, int, float]] = []
WAITS: list[float] = []
# --- Decorators ---
# TODO: step, retry, require_columns
# --- Context manager ---
# TODO: class PipelineRun
# --- Steps ---
# TODO: load_sales, clean, store_city (cached), add_city, revenue_by_region, top_cities
# --- Runs ---
# TODO: the main run, the report, the files, the failing run, the asserts
Criterion Points Full points when
Step decorator 2 @step uses functools.wraps, records name, rows and duration, and keeps the return value
Retry 3 A factory with the config delays, only transient exceptions, an injected sleep, and the last error re-raised
Validation 2 @require_columns fails before the step runs, with the step name and the missing columns
Caching 1 functools.cache on the city lookup; the cache statistics show 12 misses
Stacking order 2 @step sits above @retry, so the load_sales duration covers every attempt; the reason is written in a comment
Context manager 3 PipelineRun prints the log and status on success and on failure and never suppresses the error
Files 2 The reports are written in a temporary folder with chdir; nothing is left in the project folder
Correctness 2 Region totals match the data dictionary; the asserts pass
Type hints 1 [**P, R] (or [**P]) hints on the decorators that keep the signature
Total 18 15 or more: you are ready for module 12
  1. Record failed steps in the log too, with rows = -1 and the exception name, by moving the log entry into a finally clause.
  2. Turn PipelineRun into a ContextDecorator, so that @PipelineRun("nightly") can decorate a main() function.
  3. Add a @timeout_warning(seconds) decorator that prints a warning when a step takes longer than the limit. Test it with a fake clock.
  4. Capture the whole run’s printed output with redirect_stdout and save it as output/run.log next to the reports.
  5. Replace the fixed temporary-folder write with the atomic_write context manager of exercise M11-X04.

Try the project yourself first. Then compare. Your names and messages can differ; your region totals must not.

Reference solution

The tools: three decorators and the context manager class.

nightly_job.py (part 1: tools)
import csv
import functools
import json
import os
import tempfile
import time
from collections.abc import Callable, Sequence
from contextlib import chdir
from pathlib import Path
from types import TracebackType
from typing import Any, Self
type Table = dict[str, list[Any]]
CONFIG = json.loads(Path("data/config.json").read_text(encoding="utf-8"))
STEP_LOG: list[tuple[str, int, float]] = []
WAITS: list[float] = []
def row_count(table: Table) -> int:
return len(next(iter(table.values()), []))
def step[**P](func: Callable[P, Table]) -> Callable[P, Table]:
"""Log (name, rows, seconds) after each successful call."""
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> Table:
start = time.perf_counter()
result = func(*args, **kwargs)
STEP_LOG.append((func.__name__, row_count(result), time.perf_counter() - start))
return result
return wrapper
def retry[**P, R](
attempts: int,
delays: Sequence[float],
exceptions: tuple[type[Exception], ...] = (ConnectionError, TimeoutError),
sleep: Callable[[float], object] = time.sleep,
) -> Callable[[Callable[P, R]], Callable[P, R]]:
"""Make at most `attempts` calls; wait delays[k - 1] before retry 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
delay = delays[attempt - 1]
print(f" {func.__name__} failed ({exc}); retry in {delay}s")
sleep(delay)
raise AssertionError("unreachable")
return wrapper
return decorate
def require_columns[**P, R](*names: str) -> Callable[[Callable[P, R]], Callable[P, R]]:
"""Fail fast when the first argument lacks one of the columns."""
def decorate(func: Callable[P, R]) -> Callable[P, R]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
table = args[0]
if not isinstance(table, dict):
raise TypeError(f"{func.__name__} expects a dict of columns")
missing = [name for name in names if name not in table]
if missing:
raise ValueError(f"{func.__name__} needs columns {missing}")
return func(*args, **kwargs)
return wrapper
return decorate
class PipelineRun:
"""Clear the step log on entry; print the log and a status on exit."""
def __init__(self, name: str) -> None:
self.name = name
self.status = "not started"
def __enter__(self) -> Self:
STEP_LOG.clear()
self.start = time.perf_counter()
print(f"run {self.name}: started")
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: TracebackType | None,
) -> None:
self.seconds = time.perf_counter() - self.start
for name, rows, _ in STEP_LOG:
print(f" {name:<18} {rows:>6} rows")
if exc_type is None:
self.status = "success"
else:
self.status = f"failed ({exc_type.__name__}: {exc_value})"
print(f"run {self.name}: {self.status}")

The steps. Each one is plain logic plus decorators. @step sits on top of @retry, so the logged duration of load_sales covers every attempt.

nightly_job.py (part 2: steps)
def make_flaky_open(failures: int) -> Callable[..., Any]:
"""A fake network drive: the first `failures` opens fail."""
calls = 0
def flaky_open(path: str, **kwargs: Any) -> Any:
nonlocal calls
calls += 1
if calls <= failures:
raise ConnectionError(f"network drive not ready, call {calls}")
return open(path, **kwargs)
return flaky_open
RETRY = CONFIG["retry"] # attempts = total calls; backoff_seconds = waits
# @step above @retry: the logged duration covers every attempt and every wait.
@step
@retry(RETRY["attempts"], RETRY["backoff_seconds"], sleep=WAITS.append)
def load_sales(path: str, opener: Callable[..., Any] = open) -> Table:
names = ["store_id", "region", "quantity", "discount", "revenue"]
table: Table = {name: [] for name in names}
with opener(path, encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
for name in names:
table[name].append(row[name])
table["quantity"] = [int(q) for q in table["quantity"]]
table["discount"] = [float(d) for d in table["discount"]]
table["revenue"] = [float(r) for r in table["revenue"]]
return table
@step
@require_columns("quantity", "discount")
def clean(table: Table) -> Table:
limits = CONFIG["thresholds"]
keep = [
i
for i, (q, d) in enumerate(zip(table["quantity"], table["discount"]))
if limits["min_quantity"] <= q <= limits["max_quantity"]
and d <= limits["max_discount"]
]
return {name: [column[i] for i in keep] for name, column in table.items()}
@functools.cache
def store_city(store_id: str) -> str:
with open("data/stores.csv", encoding="utf-8", newline="") as f:
cities = {row["store_id"]: row["city"] for row in csv.DictReader(f)}
return cities[store_id]
@step
@require_columns("store_id")
def add_city(table: Table) -> Table:
return {**table, "city": [store_city(s) for s in table["store_id"]]}
def totals_by(table: Table, key: str) -> dict[str, float]:
totals: dict[str, float] = {}
for group, revenue in zip(table[key], table["revenue"]):
totals[group] = totals.get(group, 0.0) + revenue
return dict(sorted(totals.items(), key=lambda item: item[1], reverse=True))
@step
@require_columns("region", "revenue")
def revenue_by_region(table: Table) -> Table:
totals = totals_by(table, "region")
return {"region": list(totals), "revenue": [round(v, 2) for v in totals.values()]}
@step
@require_columns("city", "revenue")
def top_cities(table: Table, n: int = 3) -> Table:
best = list(totals_by(table, "city").items())[:n]
return {"city": [c for c, _ in best], "revenue": [round(v, 2) for _, v in best]}

The main run. The fake drive fails twice; the retry waits 1 and 2 seconds on the fake clock.

with PipelineRun("nightly-2024-12-31") as run:
sales = load_sales("data/sales.csv", opener=make_flaky_open(failures=2))
cleaned = clean(sales)
with_city = add_city(cleaned)
regions = revenue_by_region(with_city)
cities = top_cities(with_city)
Output
run nightly-2024-12-31: started
load_sales failed (network drive not ready, call 1); retry in 1s
load_sales failed (network drive not ready, call 2); retry in 2s
load_sales 20228 rows
clean 20228 rows
add_city 20228 rows
revenue_by_region 4 rows
top_cities 3 rows
run nightly-2024-12-31: success

The report, the recorded waits and the cache statistics:

for region, revenue in zip(regions["region"], regions["revenue"]):
print(f"{region:<6} {revenue:>12,.2f}")
for city, revenue in zip(cities["city"], cities["revenue"]):
print(f"{city:<14} {revenue:>12,.2f}")
print("waits:", WAITS)
print(store_city.cache_info())
print("all durations >= 0:", all(seconds >= 0 for _, _, seconds in STEP_LOG))
Output
East 993,683.72
South 891,766.07
North 888,229.47
West 822,844.57
New York 468,290.16
Chicago 406,532.46
Seattle 401,382.78
waits: [1, 2]
CacheInfo(hits=20216, misses=12, maxsize=None, currsize=12)
all durations >= 0: True

The files, written in a temporary folder that disappears afterwards:

project = Path.cwd()
with tempfile.TemporaryDirectory() as folder, chdir(folder):
Path("output").mkdir()
for name, table in [("region_report", regions), ("top_cities", cities)]:
with open(f"output/{name}.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.writer(f)
writer.writerow(list(table))
writer.writerows(zip(*table.values()))
print(sorted(os.listdir("output")))
print(Path("output/region_report.csv").read_text(encoding="utf-8"), end="")
print("back in the project folder:", Path.cwd() == project)
Output
['region_report.csv', 'top_cities.csv']
region,revenue
East,993683.72
South,891766.07
North,888229.47
West,822844.57
back in the project folder: True

The failing run: an upstream change dropped the discount column.

broken = {name: column for name, column in sales.items() if name != "discount"}
try:
with PipelineRun("rerun-without-discount") as rerun:
clean(broken)
except ValueError as exc:
print("caller sees:", exc)
totals = dict(zip(regions["region"], regions["revenue"]))
assert [round(totals[r]) for r in ["East", "South", "North", "West"]] == [
993684,
891766,
888229,
822845,
]
assert run.status == "success" and WAITS == [1, 2]
assert STEP_LOG == [] # the failed run logged no step
assert store_city.cache_info().misses == 12
assert rerun.status == "failed (ValueError: clean needs columns ['discount'])"
Output
run rerun-without-discount: started
run rerun-without-discount: failed (ValueError: clean needs columns ['discount'])
caller sees: clean needs columns ['discount']

How it works:

  1. @step wraps each step and appends one log entry after the call returns. row_count reads the length of the first column, so it works for every table.
  2. @retry is the lesson’s factory. attempts (3 calls in total) and the delays come from config.json, so the third call is the last chance and only the first two delays are used; WAITS.append stands in for time.sleep, so the job “waits” 3 seconds in no time.
  3. Stacking. load_sales = step(retry(...)(load_sales)). The step wrapper is outside, so it calls the retry wrapper once and logs once, after the third attempt succeeds. With the order reversed, the log would still show one entry, because @step logs only successes, but its duration would cover only the last attempt.
  4. @require_columns sits below @step. It reads the table from args[0], so the steps are called with the table by position; a keyword call (clean(table=t)) would raise IndexError (the lesson’s Example 4 shows the fix). A missing column stops the step before any work and before any log entry, with a message that names both the step and the column.
  5. Caching. add_city calls store_city 20,228 times. Only the 12 distinct store ids miss; the other 20,216 calls are hits. Each miss reads stores.csv; a plain dict built once would also work, but the cache keeps the lookup code simple.
  6. PipelineRun clears the log on entry and prints it on exit. On success the status is success. In the second run, clean raises; __exit__ prints the (empty) log and the failed status, returns None, and the error reaches the except outside. The status attribute keeps the outcome for the asserts, or for an alert email.
  7. Files. TemporaryDirectory and chdir enter in order and exit in reverse. The relative path output/... lands in the temporary folder, and the project folder stays clean.
  8. Checks. The rounded region totals equal the data dictionary. clean removed no lines, because every line of sales.csv is inside the thresholds; the step still earns its place for files like sales_raw.csv.

Alternative: pandas does the grouping in one line, df.groupby("region")["revenue"].sum() (module 25), and the decorators wrap pandas steps just as well: a @require_columns for DataFrames checks set(names) - set(df.columns). Workflow tools such as Prefect and Dagster ship @task decorators with built-in retries, logging and run tracking, built on the same ideas.