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.
Dataset
Section titled “Dataset”data/sales.csv: 20,228 order lines, 2023–2024. The job uses five columns:store_id,region,quantity,discountandrevenue.data/stores.csv: 12 stores, withstore_idandcity.data/config.json:retry.attemptsis 3 andretry.backoff_secondsis[1, 2, 4]. As in module 06,attemptsis 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;thresholdsholdsmin_quantity1,max_quantity50 andmax_discount0.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.
Requirements
Section titled “Requirements”Your script must:
- Store each table as a dict of columns (
type Table = dict[str, list[Any]]). - Provide a
@stepdecorator that appends(name, rows, seconds)to a step log after each successful call. Usefunctools.wrapsand the[**P]type parameter. - Provide a
@retry(attempts, delays, sleep=...)decorator factory that makes at mostattemptscalls, retries onlyConnectionErrorandTimeoutError, waitsdelays[k - 1]before retryk, re-raises the error of the last attempt, and accepts a fakesleep. Takeattemptsanddelaysfromconfig.json. - Provide a
@require_columns(*names)decorator factory that raisesValueErrornaming the step and the missing columns. - Cache the store-to-city lookup with
functools.cache, and report the cache statistics. - Provide a context manager class
PipelineRunthat 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. - Run five steps:
load_sales(retried),clean(thresholds),add_city,revenue_by_regionandtop_cities. Stack the decorators so that the logged duration ofload_salescovers all its attempts and waits, not only the last attempt. - Write
output/region_report.csvandoutput/top_cities.csvinside a temporary folder, withcontextlib.chdir. - Run the job a second time on a table without a
discountcolumn, and show the failed status and the error message. - End with
assertchecks: the region totals, the waits[1, 2], the cache misses and the failed status.
The main run prints exactly this:
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 rowsrun nightly-2024-12-31: successStep plan
Section titled “Step plan”-
Start with plain functions. Write
load_sales,clean,add_city,revenue_by_regionandtop_citieswithout decorators, and check their results on the real file. -
Write
@step. Time the call withtime.perf_counter(). Count the rows as the length of the first column of the returned table. Append to a module-level listSTEP_LOG. -
Write
@retry. Copy the structure of the lesson’s Example 2. Passsleep=WAITS.appendin the project, so that the waits are recorded, not slept. -
Write the fake file source. A closure counts its calls and raises
ConnectionErroron the first two. After that, it calls the realopen().load_salestakes the opener as a parameter with the defaultopen. -
Choose the stacking order.
@stepmust sit above@retry, so that its duration covers all attempts and waits. Write down why before you run it. -
Write
@require_columnsand put it below@stepon every step that reads columns. -
Write
PipelineRun.__enter__clearsSTEP_LOGand prints the start line.__exit__prints the log and the status, and returnsNone. -
Run and report. Run the five steps in a
with PipelineRun(...)block. Print the two report tables, the waits and the cache statistics. -
Write the files in
with tempfile.TemporaryDirectory() as folder, chdir(folder):, and list the folder’s contents. -
Break it on purpose. Remove the
discountcolumn from the loaded table and runcleanin a secondPipelineRun. Catch theValueErroroutside thewithblock.
A skeleton to start from:
import csvimport functoolsimport jsonimport tempfileimport timefrom collections.abc import Callable, Sequencefrom contextlib import chdirfrom pathlib import Pathfrom 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 assertsRubric
Section titled “Rubric”| 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 |
Stretch goals
Section titled “Stretch goals”- Record failed steps in the log too, with
rows = -1and the exception name, by moving the log entry into afinallyclause. - Turn
PipelineRuninto aContextDecorator, so that@PipelineRun("nightly")can decorate amain()function. - Add a
@timeout_warning(seconds)decorator that prints a warning when a step takes longer than the limit. Test it with a fake clock. - Capture the whole run’s printed output with
redirect_stdoutand save it asoutput/run.lognext to the reports. - Replace the fixed temporary-folder write with the
atomic_writecontext manager of exercise M11-X04.
Reference solution
Section titled “Reference solution”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.
import csvimport functoolsimport jsonimport osimport tempfileimport timefrom collections.abc import Callable, Sequencefrom contextlib import chdirfrom pathlib import Pathfrom types import TracebackTypefrom 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.
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.cachedef 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)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 rowsrun nightly-2024-12-31: successThe 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))East 993,683.72South 891,766.07North 888,229.47West 822,844.57New York 468,290.16Chicago 406,532.46Seattle 401,382.78waits: [1, 2]CacheInfo(hits=20216, misses=12, maxsize=None, currsize=12)all durations >= 0: TrueThe 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)['region_report.csv', 'top_cities.csv']region,revenueEast,993683.72South,891766.07North,888229.47West,822844.57back in the project folder: TrueThe 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 stepassert store_city.cache_info().misses == 12assert rerun.status == "failed (ValueError: clean needs columns ['discount'])"run rerun-without-discount: startedrun rerun-without-discount: failed (ValueError: clean needs columns ['discount'])caller sees: clean needs columns ['discount']How it works:
@stepwraps each step and appends one log entry after the call returns.row_countreads the length of the first column, so it works for every table.@retryis the lesson’s factory.attempts(3 calls in total) and the delays come fromconfig.json, so the third call is the last chance and only the first two delays are used;WAITS.appendstands in fortime.sleep, so the job “waits” 3 seconds in no time.- 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@steplogs only successes, but its duration would cover only the last attempt. @require_columnssits below@step. It reads the table fromargs[0], so the steps are called with the table by position; a keyword call (clean(table=t)) would raiseIndexError(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.- Caching.
add_citycallsstore_city20,228 times. Only the 12 distinct store ids miss; the other 20,216 calls are hits. Each miss readsstores.csv; a plain dict built once would also work, but the cache keeps the lookup code simple. PipelineRunclears the log on entry and prints it on exit. On success the status issuccess. In the second run,cleanraises;__exit__prints the (empty) log and the failed status, returnsNone, and the error reaches theexceptoutside. The status attribute keeps the outcome for the asserts, or for an alert email.- Files.
TemporaryDirectoryandchdirenter in order and exit in reverse. The relative pathoutput/...lands in the temporary folder, and the project folder stays clean. - Checks. The rounded region totals equal the data dictionary.
cleanremoved no lines, because every line ofsales.csvis inside the thresholds; the step still earns its place for files likesales_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.