Skip to content

11. Decorators and context managers — Exercises

These exercises practice every idea of the decorators and context managers lesson. They use the course datasets: data/sales.csv, data/sales_raw.csv, data/customers.csv, data/stores.csv, data/readings.txt, data/config.json, the monthly files in data/reports/ and the saved API responses in data/api/.

How to work:

  1. Read the task and the expected output.
  2. Copy the setup block and the starter code into a script, and replace each to-do comment with your code.
  3. Run the script from your project folder. Compare your output with the expected output.
  4. Stuck? Open one hint at a time. Open the solution only after a real attempt.

Each solution ends with assert checks. Add the same checks to your own code.

Every exercise starts from these imports. The solutions assume them.

import csv
import functools
import inspect
import io
import json
import math
import os
import tempfile
import time
from collections.abc import Callable, Iterator, Sequence
from contextlib import ExitStack, chdir, contextmanager, redirect_stdout, suppress
from pathlib import Path
from types import TracebackType
from typing import Any, Self

M11-W01 · Run cleaning steps named in a config

Section titled “M11-W01 · Run cleaning steps named in a config”
Warm-up

A sensor job reads its cleaning steps from a config as a list of names. Write the three step functions, map each name to its function in a dict, then run the steps in the configured order on raw. After each step, print the step’s __name__ and the current values. Round the Fahrenheit values to 1 decimal.

Expected output
strip_text: ['21.7', '22.1', '19.8']
to_float: [21.7, 22.1, 19.8]
c_to_f: [71.1, 71.8, 67.6]
Starter
raw = [" 21.7", "22.1 ", " 19.8 "]
config_steps = ["strip_text", "to_float", "c_to_f"]
def strip_text(values: list[str]) -> list[str]:
... # TODO: strip spaces from each value
# TODO: write to_float and c_to_f (°F = °C * 9 / 5 + 32, rounded to 1 decimal)
# TODO: build STEPS = {name: function}, then run the steps in config order
Hint 1

A dict value can be a function: {"strip_text": strip_text}. No parentheses after the name.

Hint 2

Loop over config_steps, look up step = STEPS[name], then values = step(values) and print(f"{step.__name__}: {values}").

Solution
raw = [" 21.7", "22.1 ", " 19.8 "]
config_steps = ["strip_text", "to_float", "c_to_f"]
def strip_text(values: list[str]) -> list[str]:
return [v.strip() for v in values]
def to_float(values: list[str]) -> list[float]:
return [float(v) for v in values]
def c_to_f(values: list[float]) -> list[float]:
return [round(v * 9 / 5 + 32, 1) for v in values]
STEPS = {"strip_text": strip_text, "to_float": to_float, "c_to_f": c_to_f}
values: Any = raw
for name in config_steps:
step = STEPS[name]
values = step(values)
print(f"{step.__name__}: {values}")
assert values == [71.1, 71.8, 67.6]
assert all(callable(f) for f in STEPS.values())
Output
strip_text: ['21.7', '22.1', '19.8']
to_float: [21.7, 22.1, 19.8]
c_to_f: [71.1, 71.8, 67.6]

How it works:

  1. Each step is a normal function. The dict stores the function objects, not their results.
  2. The loop looks up each configured name and calls the function it finds.
  3. step.__name__ comes from the function object itself, so the report always matches the code.
  4. values: Any tells a type checker that the variable changes type from step to step (text, then numbers).

Alternative: skip the dict and use globals()[name] to find the function by its name. Do not: any name in the module becomes callable from the config, including ones you never meant to expose. An explicit dict is a whitelist.

M11-W02 · Predict the output: decoration time and call time

Section titled “M11-W02 · Predict the output: decoration time and call time”
Warm-up

Predict the output: write down every line this code prints, in order. Then run it.

Acceptance criteria:

  • You wrote your prediction for every line before you ran the code.
  • Your prediction matches the Output in the solution, line by line.
  • You can say which lines print at decoration time and which at call time.
Starter
def register(func):
print(f"register {func.__name__}")
def wrapper(*args, **kwargs):
print(f"call {func.__name__}")
return func(*args, **kwargs)
return wrapper
print("start")
@register
def load():
return 3
@register
def clean(n):
return n - 1
print("defined")
print(clean(load()))
# TODO: write your prediction for each line before you run it
Hint 1

A decorator runs when Python executes the def statement, even if nobody calls the function.

Hint 2

In clean(load()), Python evaluates the argument load() first.

Solution
def register(func):
print(f"register {func.__name__}")
def wrapper(*args, **kwargs):
print(f"call {func.__name__}")
return func(*args, **kwargs)
return wrapper
print("start")
@register
def load():
return 3
@register
def clean(n):
return n - 1
print("defined")
print(clean(load()))
assert clean.__name__ == "wrapper"
Output
start
register load
register clean
defined
call load
call clean
2

How it works:

  1. start prints first, because it is the first statement.
  2. Each @register line runs the decorator body once, when its def executes. So register load and register clean print before defined.
  3. clean(load()) evaluates the inner call first: the load wrapper prints call load and returns 3. Then the clean wrapper prints call clean and returns 2.
  4. The assert shows a side effect: without functools.wraps, the decorated clean is named wrapper.

Alternative: add @functools.wraps(func) to the wrapper. The output stays the same, and clean.__name__ becomes 'clean'.

Warm-up

Write a decorator log_calls that prints the function’s name, its positional arguments and its keyword arguments before each call, then returns the result. Use functools.wraps. Apply it to scale, call scale([1.0, 2.5], factor=2), print the result and the function’s name.

Expected output
call scale args=([1.0, 2.5],) kwargs={'factor': 2}
[2.0, 5.0]
scale
Starter
def log_calls(func):
# TODO: define a wrapper with *args and **kwargs, decorated with functools.wraps
# TODO: print the call, then return the result of func
...
@log_calls
def scale(values: list[float], factor: float = 1.0) -> list[float]:
return [v * factor for v in values]
Hint 1

Inside the wrapper, args is a tuple and kwargs is a dict. An f-string prints both: f"args={args}".

Hint 2

The wrapper ends with return func(*args, **kwargs), and the decorator ends with return wrapper.

Solution
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"call {func.__name__} args={args} kwargs={kwargs}")
return func(*args, **kwargs)
return wrapper
@log_calls
def scale(values: list[float], factor: float = 1.0) -> list[float]:
return [v * factor for v in values]
result = scale([1.0, 2.5], factor=2)
print(result)
print(scale.__name__)
assert result == [2.0, 5.0]
assert scale.__name__ == "scale"
Output
call scale args=([1.0, 2.5],) kwargs={'factor': 2}
[2.0, 5.0]
scale

How it works:

  1. *args collects the positional arguments into a tuple: one list here, so ([1.0, 2.5],) with a trailing comma.
  2. **kwargs collects the keyword arguments into a dict: {'factor': 2}.
  3. func(*args, **kwargs) unpacks both again, so scale receives exactly what the caller passed.
  4. functools.wraps copies the name, so scale.__name__ is 'scale'.

Alternative: use the logging module (module 06) instead of print(), so you can switch the messages off with a log level: logging.getLogger(func.__module__).debug(...).

M11-W04 · Fix the bug: the metric returns None

Section titled “M11-W04 · Fix the bug: the metric returns None”
Warm-up

Fix the bug: this decorated metric prints None instead of the mean price of three products from data/products.csv. Find the bug and fix it.

Expected output
computing mean_price
542.66
Starter
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"computing {func.__name__}")
func(*args, **kwargs)
return wrapper
@log_calls
def mean_price(prices: list[float]) -> float:
return round(sum(prices) / len(prices), 2)
print(mean_price([79.99, 249.0, 1299.0]))
# TODO: find and fix the bug
Hint 1

What does a Python function return when it reaches its end without a return statement?

Solution
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"computing {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log_calls
def mean_price(prices: list[float]) -> float:
return round(sum(prices) / len(prices), 2)
result = mean_price([79.99, 249.0, 1299.0])
print(result)
assert result == 542.66
Output
computing mean_price
542.66

How it works:

  1. The wrapper called func but did not return its value. A function without return returns None.
  2. Adding return passes the original result back to the caller.
  3. The mean of 79.99, 249.00 and 1,299.00 is 1,627.99 / 3 = 542.66.

Alternative: store the result in a variable when the wrapper has work to do after the call: result = func(*args, **kwargs), then the extra code, then return result.

M11-W05 · Fix the bug: every step is called wrapper

Section titled “M11-W05 · Fix the bug: every step is called wrapper”
Warm-up

Fix the bug: a pipeline report prints the name of each step, but both steps show up as wrapper and the docstring is gone. Fix the decorator so that the report shows the real names and the first docstring.

Expected output
['drop_returns', 'cap_bulk']
Remove lines with quantity <= 0.
Starter
def check_not_empty(func):
def wrapper(quantities):
if not quantities:
raise ValueError(f"{func.__name__} got no data")
return func(quantities)
return wrapper
@check_not_empty
def drop_returns(quantities: list[int]) -> list[int]:
"""Remove lines with quantity <= 0."""
return [q for q in quantities if q > 0]
@check_not_empty
def cap_bulk(quantities: list[int]) -> list[int]:
"""Cap bulk lines at 50 units."""
return [min(q, 50) for q in quantities]
steps = [drop_returns, cap_bulk]
print([step.__name__ for step in steps])
print(steps[0].__doc__)
# TODO: fix the decorator
Hint 1

One line from functools copies the metadata of func to the wrapper.

Solution
def check_not_empty(func):
@functools.wraps(func)
def wrapper(quantities):
if not quantities:
raise ValueError(f"{func.__name__} got no data")
return func(quantities)
return wrapper
@check_not_empty
def drop_returns(quantities: list[int]) -> list[int]:
"""Remove lines with quantity <= 0."""
return [q for q in quantities if q > 0]
@check_not_empty
def cap_bulk(quantities: list[int]) -> list[int]:
"""Cap bulk lines at 50 units."""
return [min(q, 50) for q in quantities]
steps = [drop_returns, cap_bulk]
print([step.__name__ for step in steps])
print(steps[0].__doc__)
assert [s.__name__ for s in steps] == ["drop_returns", "cap_bulk"]
assert cap_bulk(drop_returns([1, -2, 250])) == [1, 50]
Output
['drop_returns', 'cap_bulk']
Remove lines with quantity <= 0.

How it works:

  1. Without wraps, each decorated name refers to a function called wrapper, with no docstring.
  2. @functools.wraps(func) copies __name__, __doc__ and the other metadata from func.
  3. The error message inside the wrapper already used func.__name__, so it was correct before the fix. Only code outside the decorator saw the wrong name.

Alternative: functools.update_wrapper(wrapper, func) after the inner def does the same job. wraps is the decorator form of update_wrapper.

M11-W06 · Write a section context manager

Section titled “M11-W06 · Write a section context manager”
Warm-up

Write a class Section whose with block prints a header line before the block and a footer line after it. The constructor takes a title. Use it to print a small summary of three sample order values for store S01: 79.99, 249.00 and 129.95 USD.

Expected output
== Store S01 (Chicago) ==
orders: 3
revenue: 458.94
== end Store S01 (Chicago) ==
Starter
class Section:
def __init__(self, title: str) -> None:
self.title = title
# TODO: __enter__ prints "== <title> ==" and returns self
# TODO: __exit__ prints "== end <title> =="
orders = [79.99, 249.00, 129.95]
with Section("Store S01 (Chicago)"):
print("orders:", len(orders))
print("revenue:", round(sum(orders), 2))
Hint 1

__enter__(self) takes only self. __exit__ takes self and three more arguments: exc_type, exc_value, traceback.

Hint 2

__exit__ can return None. That lets any exception continue, which is what you want here.

Solution
class Section:
def __init__(self, title: str) -> None:
self.title = title
self.closed = False
def __enter__(self) -> Self:
print(f"== {self.title} ==")
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: TracebackType | None,
) -> None:
print(f"== end {self.title} ==")
self.closed = True
orders = [79.99, 249.00, 129.95]
with Section("Store S01 (Chicago)") as section:
print("orders:", len(orders))
print("revenue:", round(sum(orders), 2))
assert section.closed
Output
== Store S01 (Chicago) ==
orders: 3
revenue: 458.94
== end Store S01 (Chicago) ==

How it works:

  1. with Section(...) creates the instance and calls its __enter__, which prints the header and returns the instance for as section.
  2. The block body runs.
  3. __exit__ prints the footer and marks the section as closed. It would run the same way if the body raised an error.

Alternative: the same in three lines with @contextmanager: print the header, yield, and print the footer inside finally.

M11-W07 · Skip bad readings with suppress

Section titled “M11-W07 · Skip bad readings with suppress”
Warm-up

data/readings.txt has 43 lines; three of them (error, an empty line and n/a) are not numbers. Read the file, convert each line with float() and skip the bad ones with contextlib.suppress. Print the count and the mean, rounded to 2 decimals.

Expected output
40 valid readings, mean 21.06 °C
Starter
readings: list[float] = []
with open("data/readings.txt", encoding="utf-8") as f:
for line in f:
... # TODO: append float(line), skipping lines that raise ValueError
# TODO: print the count and the mean
Hint 1

with suppress(ValueError): goes inside the loop, around the one line that can fail.

Solution
readings: list[float] = []
with open("data/readings.txt", encoding="utf-8") as f:
for line in f:
with suppress(ValueError):
readings.append(float(line))
mean = sum(readings) / len(readings)
print(f"{len(readings)} valid readings, mean {mean:.2f} °C")
assert len(readings) == 40
assert 19.3 <= min(readings) and max(readings) <= 22.9
Output
40 valid readings, mean 21.06 °C

How it works:

  1. float() ignores the line break at the end of each line, and raises ValueError for error, "" and n/a.
  2. suppress(ValueError) ends that iteration’s with block quietly. The append never runs for a bad line.
  3. The other 40 lines become floats.

Alternative: the explicit form is try: readings.append(float(line)) and except ValueError: pass. It does the same thing; suppress says it in one line. Use try/except when you need to count or log the bad lines.

M11-W08 · Predict the output: two stacked decorators

Section titled “M11-W08 · Predict the output: two stacked decorators”
Warm-up

Predict the output: two decorators each wrap the result in a label. Write down both printed lines, then run the code.

Acceptance criteria:

  • You wrote both lines before you ran the code.
  • Your prediction matches the Output in the solution.
  • You can explain why swapping the decorators swaps the labels.
Starter
def label(name):
def decorate(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return f"{name}({func(*args, **kwargs)})"
return wrapper
return decorate
@label("round")
@label("clip")
def score(x):
return x
@label("clip")
@label("round")
def score_2(x):
return x
print(score(0.87))
print(score_2(0.87))
# TODO: write your prediction before you run it
Hint 1

Rewrite the first stack without @: score = label("round")(label("clip")(score)).

Hint 2

The inner wrapper finishes first, so its label sits closest to the number.

Solution
def label(name):
def decorate(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return f"{name}({func(*args, **kwargs)})"
return wrapper
return decorate
@label("round")
@label("clip")
def score(x):
return x
@label("clip")
@label("round")
def score_2(x):
return x
print(score(0.87))
print(score_2(0.87))
assert score(0.5) == "round(clip(0.5))"
Output
round(clip(0.87))
clip(round(0.87))

How it works:

  1. The bottom decorator wraps first. For score, clip wraps the function, then round wraps the clip wrapper.
  2. At call time, the round wrapper calls the clip wrapper, which calls score. The clip wrapper returns clip(0.87), and the round wrapper wraps that in round(...).
  3. The text reads like the nested calls round(clip(x)): the top decorator is the outermost function.

Alternative: apply the decorators by hand to see the nesting: label("round")(label("clip")(lambda x: x))(0.87) gives the same text.

M11-C01 · Count the calls of a quantity check

Section titled “M11-C01 · Count the calls of a quantity check”
Core

Write a decorator count_calls that counts the calls of a function in an attribute calls on the wrapper. Use it on is_valid_quantity, which applies the min_quantity and max_quantity thresholds of data/config.json. Check every quantity in data/sales_raw.csv and print the counts.

Expected output
checked 1200 lines, 1190 valid
calls: 1200
rejected: [-3, -2, -2, -2, -1, -1, 250, 500, 999, 1000]
Starter
with open("data/config.json", encoding="utf-8") as f:
thresholds = json.load(f)["thresholds"]
def count_calls(func):
... # TODO: wrapper that adds 1 to wrapper.calls, then calls func
@count_calls
def is_valid_quantity(quantity: int) -> bool:
return thresholds["min_quantity"] <= quantity <= thresholds["max_quantity"]
# TODO: read data/sales_raw.csv with csv.DictReader and check every quantity
# TODO: print the number of lines, the number of valid lines and the call count
Hint 1

A function is an object, so wrapper.calls = 0 after the inner def creates the counter.

Hint 2

Inside the wrapper, wrapper.calls += 1 works because Python looks up wrapper in the enclosing scope at call time.

Solution
with open("data/config.json", encoding="utf-8") as f:
thresholds = json.load(f)["thresholds"]
def count_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
wrapper.calls += 1
return func(*args, **kwargs)
wrapper.calls = 0
return wrapper
@count_calls
def is_valid_quantity(quantity: int) -> bool:
return thresholds["min_quantity"] <= quantity <= thresholds["max_quantity"]
with open("data/sales_raw.csv", encoding="utf-8", newline="") as f:
quantities = [int(row["quantity"]) for row in csv.DictReader(f)]
valid = [q for q in quantities if is_valid_quantity(q)]
print(f"checked {len(quantities)} lines, {len(valid)} valid")
print("calls:", is_valid_quantity.calls)
print("rejected:", sorted(q for q in quantities if not 1 <= q <= 50))
assert is_valid_quantity.calls == len(quantities) == 1200
assert len(valid) == 1190
Output
checked 1200 lines, 1190 valid
calls: 1200
rejected: [-3, -2, -2, -2, -1, -1, 250, 500, 999, 1000]

How it works:

  1. wrapper.calls = 0 stores the counter on the wrapper object. The decorator returns that same object, so is_valid_quantity.calls reads it.
  2. Each call adds 1 before it forwards the arguments.
  3. sales_raw.csv has 6 negative and 4 absurd quantities, so 1,190 of 1,200 lines pass. The rejected list shows exactly those 10 values.

Alternative: keep the counter in a closure with nonlocal count and expose it with a small function wrapper.get_count = lambda: count. The attribute version is shorter and easier to read.

M11-C02 · Collect every duration per step

Section titled “M11-C02 · Collect every duration per step”
Core

Write a decorator factory timed(registry) that appends the duration of each call to registry[name], a list per function name. Decorate two steps that work on the customer records of data/customers.csv, run them three times, and print how many durations each step collected and whether all of them are positive. Do not print the durations themselves.

Expected output
churn rate: 19.26%
load_customers: 3 runs, all positive: True
churn_rate: 3 runs, all positive: True
Starter
def timed(registry: dict[str, list[float]]):
... # TODO: decorate -> wrapper; append time.perf_counter() differences
RUNS: dict[str, list[float]] = {}
@timed(RUNS)
def load_customers(path: str) -> list[dict[str, str]]:
with open(path, encoding="utf-8", newline="") as f:
return list(csv.DictReader(f))
@timed(RUNS)
def churn_rate(rows: list[dict[str, str]]) -> float:
return sum(row["churned"] == "1" for row in rows) / len(rows)
# TODO: run both steps three times, then print the report
Hint 1

registry.setdefault(func.__name__, []).append(seconds) creates the list the first time and appends to it every time.

Hint 2

Measure in a try/finally, so a failing call still records its duration.

Solution
def timed[**P, R](
registry: dict[str, list[float]],
) -> Callable[[Callable[P, R]], Callable[P, R]]:
def decorate(func: Callable[P, R]) -> Callable[P, R]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
start = time.perf_counter()
try:
return func(*args, **kwargs)
finally:
seconds = time.perf_counter() - start
registry.setdefault(func.__name__, []).append(seconds)
return wrapper
return decorate
RUNS: dict[str, list[float]] = {}
@timed(RUNS)
def load_customers(path: str) -> list[dict[str, str]]:
with open(path, encoding="utf-8", newline="") as f:
return list(csv.DictReader(f))
@timed(RUNS)
def churn_rate(rows: list[dict[str, str]]) -> float:
return sum(row["churned"] == "1" for row in rows) / len(rows)
for _ in range(3):
rate = churn_rate(load_customers("data/customers.csv"))
print(f"churn rate: {rate:.2%}")
for name, durations in RUNS.items():
print(f"{name}: {len(durations)} runs, all positive: {min(durations) > 0}")
counts = {name: len(d) for name, d in RUNS.items()}
assert counts == {"load_customers": 3, "churn_rate": 3}
Output
churn rate: 19.26%
load_customers: 3 runs, all positive: True
churn_rate: 3 runs, all positive: True

How it works:

  1. timed(RUNS) runs first and returns decorate, which wraps the step. Each step gets its own wrapper, but both write into the same registry.
  2. setdefault returns the existing list for a name, or stores and returns a new empty one.
  3. The finally clause records a duration on success and on failure.
  4. row["churned"] == "1" is a bool, and sum() counts True as 1. The rate matches the data dictionary: 963 of 5,000 customers.

Alternative: a collections.defaultdict(list) as the registry removes the need for setdefault: registry[func.__name__].append(seconds).

M11-C03 · Round metric results with a decorator factory

Section titled “M11-C03 · Round metric results with a decorator factory”
Core

Write a decorator factory round_result(digits) that rounds the return value of a metric. Apply it with 2 digits to the mean monthly charge and with 3 digits to the churn rate of data/customers.csv. Print both metrics, and show that functools.wraps kept the docstring.

Expected output
mean monthly charges: 60.84
churn rate: 0.193
Average monthly charge per customer, in USD.
Starter
with open("data/customers.csv", encoding="utf-8", newline="") as f:
customers = list(csv.DictReader(f))
def round_result(digits: int):
... # TODO: three levels: settings -> decorate(func) -> wrapper
# TODO: decorate mean_monthly_charges (2 digits) and churn_rate (3 digits)
Hint 1

@round_result(2) means func = round_result(2)(func). round_result(2) must return a decorator.

Hint 2

The wrapper is return round(func(*args, **kwargs), digits). digits comes from the outermost function through the closure.

Solution
with open("data/customers.csv", encoding="utf-8", newline="") as f:
customers = list(csv.DictReader(f))
def round_result[**P](
digits: int,
) -> Callable[[Callable[P, float]], Callable[P, float]]:
def decorate(func: Callable[P, float]) -> Callable[P, float]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> float:
return round(func(*args, **kwargs), digits)
return wrapper
return decorate
@round_result(2)
def mean_monthly_charges(rows: list[dict[str, str]]) -> float:
"""Average monthly charge per customer, in USD."""
return sum(float(r["monthly_charges"]) for r in rows) / len(rows)
@round_result(3)
def churn_rate(rows: list[dict[str, str]]) -> float:
"""Share of customers who churned."""
return sum(r["churned"] == "1" for r in rows) / len(rows)
print("mean monthly charges:", mean_monthly_charges(customers))
print("churn rate:", churn_rate(customers))
print(mean_monthly_charges.__doc__)
assert churn_rate(customers) == 0.193
assert mean_monthly_charges.__name__ == "mean_monthly_charges"
Output
mean monthly charges: 60.84
churn rate: 0.193
Average monthly charge per customer, in USD.

How it works:

  1. The factory takes digits and returns decorate. decorate takes the metric and returns wrapper. wrapper computes and rounds.
  2. Each @round_result(...) line creates a separate decorate with its own digits.
  3. The hints use only **P: the return type is always float, so no R is needed.
  4. The churn rate is 963 / 5,000 = 0.1926, which rounds to 0.193.

Alternative: round at display time with an f-string (f"{rate:.3f}") and keep the full precision in the returned value. That is better when another calculation uses the metric later. The decorator fits when the rounded value is the official number, for example in a report table.

M11-C04 · Retry a flaky API call with exponential backoff

Section titled “M11-C04 · Retry a flaky API call with exponential backoff”
Core

Write a decorator factory retry(attempts, base_delay, sleep=time.sleep). It calls the function up to attempts times. After failed attempt k (counting from 0), it waits base_delay * 2**k seconds. It retries only ConnectionError and TimeoutError. Test it with a fake fetch that fails three times before it returns data/api/products_page_2.json, and with a fake sleep that records the waits.

Expected output
page 2 of 3
first product: P011 Waterproof Rain Jacket
waits: [0.5, 1.0, 2.0]
gave up: attempt 3 timed out | waits: [0.5, 1.0]
Starter
def make_flaky_fetch(failures: int) -> Callable[[str], dict[str, Any]]:
calls = 0
def fetch(path: str) -> dict[str, Any]:
nonlocal calls
calls += 1
if calls <= failures:
raise TimeoutError(f"attempt {calls} timed out")
return json.loads(Path(path).read_text(encoding="utf-8"))
return fetch
def retry(attempts: int, base_delay: float, sleep=time.sleep):
... # TODO: decorator factory; wait base_delay * 2**k after failure k
waits: list[float] = []
# TODO: decorate make_flaky_fetch(failures=3) with retry(4, 0.5, sleep=waits.append)
# TODO: fetch page 2 and print the page number, the first product and the waits
Hint 1

Loop for k in range(attempts):. Return as soon as a call succeeds. On the last attempt, re-raise the error with a bare raise.

Hint 2

waits.append is a function that takes one argument, so it can stand in for time.sleep.

Solution
def make_flaky_fetch(failures: int) -> Callable[[str], dict[str, Any]]:
calls = 0
def fetch(path: str) -> dict[str, Any]:
nonlocal calls
calls += 1
if calls <= failures:
raise TimeoutError(f"attempt {calls} timed out")
return json.loads(Path(path).read_text(encoding="utf-8"))
return fetch
def retry[**P, R](
attempts: int,
base_delay: float,
sleep: Callable[[float], object] = time.sleep,
) -> Callable[[Callable[P, R]], Callable[P, R]]:
def decorate(func: Callable[P, R]) -> Callable[P, R]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
for k in range(attempts):
try:
return func(*args, **kwargs)
except (ConnectionError, TimeoutError):
if k == attempts - 1:
raise
sleep(base_delay * 2**k)
raise AssertionError("unreachable")
return wrapper
return decorate
waits: list[float] = []
fetch_page = retry(4, 0.5, sleep=waits.append)(make_flaky_fetch(failures=3))
page = fetch_page("data/api/products_page_2.json")
print("page", page["page"], "of", page["total_pages"])
print("first product:", page["data"][0]["id"], page["data"][0]["name"])
print("waits:", waits)
assert waits == [0.5, 1.0, 2.0]
waits.clear()
always_down = retry(3, 0.5, sleep=waits.append)(make_flaky_fetch(failures=99))
try:
always_down("data/api/products_page_2.json")
except TimeoutError as exc:
print("gave up:", exc, "| waits:", waits)
assert waits == [0.5, 1.0]
Output
page 2 of 3
first product: P011 Waterproof Rain Jacket
waits: [0.5, 1.0, 2.0]
gave up: attempt 3 timed out | waits: [0.5, 1.0]

How it works:

  1. The loop makes up to attempts calls. A success returns at once.
  2. A listed exception on attempt k waits base_delay * 2**k: 0.5, 1.0 and 2.0 seconds for k = 0, 1, 2.
  3. On the last attempt, the bare raise re-raises the same exception, so the caller sees the real error.
  4. The final raise AssertionError("unreachable") runs only for attempts=0, which makes no sense. It also tells a type checker that the function cannot end without returning a value.
  5. The second test fails every time: 3 attempts, 2 waits, then the original TimeoutError reaches the caller.

Alternative: the tenacity library offers a full retry decorator (@retry(stop=stop_after_attempt(4), wait=wait_exponential(...))), with jitter and logging. Write your own once to understand it; use the library in production.

M11-C05 · Reject impossible model outputs

Section titled “M11-C05 · Reject impossible model outputs”
Core

A churn model must return probabilities between 0 and 1. Write a decorator check_probabilities that checks every value of the returned list and raises ValueError with the function name, the bad value and its index. Apply it to a correct logistic scorer and to a buggy scorer that forgot the logistic function. Print the good scores and the error message of the bad one.

Expected output
[0.769, 0.5, 0.047]
rejected: churn_score_raw returned 1.2 at index 0
Starter
def check_probabilities(func):
... # TODO: call func, check each value is in [0, 1], else raise ValueError
@check_probabilities
def churn_score(tenure_months: list[int]) -> list[float]:
return [round(1 / (1 + math.exp(0.15 * t - 1.5)), 3) for t in tenure_months]
@check_probabilities
def churn_score_raw(tenure_months: list[int]) -> list[float]:
return [round(1.5 - 0.15 * t, 3) for t in tenure_months] # bug: no logistic
tenures = [2, 10, 30]
# TODO: print churn_score(tenures); call churn_score_raw and print its error
Hint 1

Validate after the call: result = func(*args, **kwargs), then loop over enumerate(result).

Hint 2

0.0 <= p <= 1.0 is the check. Catch the error in the calling code with except ValueError as exc: and print exc.

Solution
def check_probabilities[**P](
func: Callable[P, list[float]],
) -> Callable[P, list[float]]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> list[float]:
result = func(*args, **kwargs)
for i, p in enumerate(result):
if not 0.0 <= p <= 1.0:
raise ValueError(f"{func.__name__} returned {p} at index {i}")
return result
return wrapper
@check_probabilities
def churn_score(tenure_months: list[int]) -> list[float]:
return [round(1 / (1 + math.exp(0.15 * t - 1.5)), 3) for t in tenure_months]
@check_probabilities
def churn_score_raw(tenure_months: list[int]) -> list[float]:
return [round(1.5 - 0.15 * t, 3) for t in tenure_months] # bug: no logistic
tenures = [2, 10, 30]
scores = churn_score(tenures)
print(scores)
try:
churn_score_raw(tenures)
except ValueError as exc:
print("rejected:", exc)
message = str(exc)
assert all(0 <= p <= 1 for p in scores)
assert message == "churn_score_raw returned 1.2 at index 0"
Output
[0.769, 0.5, 0.047]
rejected: churn_score_raw returned 1.2 at index 0

How it works:

  1. The wrapper calls the scorer first, then checks the result. This is an output validator: it guards the caller from a broken function.
  2. The logistic function 1/(1+e−z)1 / (1 + e^{-z}) always gives a value between 0 and 1, so churn_score passes. Short tenure gives a high churn risk, as in data/customers.csv.
  3. churn_score_raw returns 1.5 - 0.15 * 2 = 1.2 for the first customer, so the wrapper raises at index 0.

Alternative: return a cleaned result instead of raising, for example with min(max(p, 0.0), 1.0). That hides the bug in the model. In a pipeline, a loud failure is better than a silently wrong probability.

M11-C06 · Interpret: why the store cache has 11 misses

Section titled “M11-C06 · Interpret: why the store cache has 11 misses”
Core

Interpret a result: store_city(store_id) opens data/stores.csv on every call. Look up the city for the first 1,000 lines of data/sales.csv, first plain, then cached with functools.cache, and print the file reads and cache_info(). The course has 12 stores, but the cache reports only 11 misses. Explain in two sentences what the hits and the misses count and why there are 11 misses. Then prove the explanation with data: print the dates that the 1,000 lines cover and the date of store S12’s first sale.

Expected output
uncached file reads: 1000
cached file reads: 11
CacheInfo(hits=989, misses=11, maxsize=None, currsize=11)
stores seen: ['S01', 'S02', 'S03', 'S04', 'S05', 'S06', 'S07', 'S08', 'S09', 'S10', 'S11']
lines cover: 2023-01-01 to 2023-02-25
first S12 sale: 2023-06-15
Starter
reads: list[str] = []
def store_city(store_id: str) -> str:
reads.append(store_id)
with open("data/stores.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
if row["store_id"] == store_id:
return row["city"]
raise KeyError(store_id)
with open("data/sales.csv", encoding="utf-8", newline="") as f:
first_lines = [row for _, row in zip(range(1000), csv.DictReader(f))]
# TODO: look up the city of every line, count the reads
# TODO: cache store_city with functools.cache, clear reads, repeat, print cache_info()
# TODO: write your explanation of hits and misses as a comment
# TODO: print the date range of first_lines and the first sale date of S12
Hint 1

cached_city = functools.cache(store_city) caches a function that already exists, like @functools.cache would.

Hint 2

A miss happens once per distinct store id. How many stores had sales in the first weeks of 2023? Check data/stores.csv for a store that opened later.

Solution
reads: list[str] = []
def store_city(store_id: str) -> str:
reads.append(store_id)
with open("data/stores.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
if row["store_id"] == store_id:
return row["city"]
raise KeyError(store_id)
with open("data/sales.csv", encoding="utf-8", newline="") as f:
first_lines = [row for _, row in zip(range(1000), csv.DictReader(f))]
cities = [store_city(row["store_id"]) for row in first_lines]
print("uncached file reads:", len(reads))
reads.clear()
cached_city = functools.cache(store_city)
cities_cached = [cached_city(row["store_id"]) for row in first_lines]
print("cached file reads:", len(reads))
print(cached_city.cache_info())
print("stores seen:", sorted(set(reads)))
# Interpretation: a miss is the first lookup of a store id and reads the file;
# every repeat is a hit. 11 misses mean only 11 distinct stores appear here.
dates = [row["order_date"] for row in first_lines]
print("lines cover:", dates[0], "to", dates[-1])
with open("data/sales.csv", encoding="utf-8", newline="") as f:
rows = csv.DictReader(f)
s12_first = next(r["order_date"] for r in rows if r["store_id"] == "S12")
print("first S12 sale:", s12_first)
assert cities == cities_cached
assert len(reads) == cached_city.cache_info().misses == 11
assert s12_first > dates[-1]
Output
uncached file reads: 1000
cached file reads: 11
CacheInfo(hits=989, misses=11, maxsize=None, currsize=11)
stores seen: ['S01', 'S02', 'S03', 'S04', 'S05', 'S06', 'S07', 'S08', 'S09', 'S10', 'S11']
lines cover: 2023-01-01 to 2023-02-25
first S12 sale: 2023-06-15

How it works:

  1. Without the cache, every line opens the file: 1,000 reads.
  2. With functools.cache, the first lookup of each store id is a miss that reads the file. Every later lookup is a hit.
  3. Interpretation. Hits plus misses equal the 1,000 calls. Each miss is the first lookup of one store id, so 11 misses mean 11 distinct stores. The missing store is S12 (Denver): it opened on 2023-06-15, and its first sale comes months after the last of the 1,000 lines, which cover 1 January to 25 February 2023. The check s12_first > dates[-1] proves it with the data.
  4. maxsize=None in the statistics means the cache has no size limit, which is what functools.cache is.

Alternative: read data/stores.csv once into a dict, {row["store_id"]: row["city"] for row in ...}, and look up from it. For a small lookup table that is simpler than a cache. A cache fits when the full table is expensive to build, or when you cannot know the keys in advance, such as with API calls.

M11-C07 · Refactor: move repeated timing code into a decorator

Section titled “M11-C07 · Refactor: move repeated timing code into a decorator”
Core

Refactor: three sensor steps repeat the same five lines of timing code. Move the timing into one decorator timed that writes to TIMINGS, and remove the duplication from the steps. The results and the list of timed step names must stay the same.

Expected output
21.06
['parse', 'clip', 'mean']
Starter
TIMINGS: dict[str, float] = {}
def parse(lines: list[str]) -> list[float]:
start = time.perf_counter()
values = []
for line in lines:
with suppress(ValueError):
values.append(float(line))
TIMINGS["parse"] = time.perf_counter() - start
return values
def clip(values: list[float]) -> list[float]:
start = time.perf_counter()
result = [min(max(v, 19.0), 23.0) for v in values]
TIMINGS["clip"] = time.perf_counter() - start
return result
def mean(values: list[float]) -> float:
start = time.perf_counter()
result = round(sum(values) / len(values), 2)
TIMINGS["mean"] = time.perf_counter() - start
return result
lines = Path("data/readings.txt").read_text(encoding="utf-8").splitlines()
print(mean(clip(parse(lines))))
print(list(TIMINGS))
# TODO: write @timed and remove the timing lines from the three steps
Hint 1

The repeated lines are: read the clock, run the body, store the difference under the function’s name.

Hint 2

Each step then shrinks to its real logic and can return its result directly.

Solution
TIMINGS: dict[str, float] = {}
def timed[**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:
TIMINGS[func.__name__] = time.perf_counter() - start
return wrapper
@timed
def parse(lines: list[str]) -> list[float]:
values = []
for line in lines:
with suppress(ValueError):
values.append(float(line))
return values
@timed
def clip(values: list[float]) -> list[float]:
return [min(max(v, 19.0), 23.0) for v in values]
@timed
def mean(values: list[float]) -> float:
return round(sum(values) / len(values), 2)
lines = Path("data/readings.txt").read_text(encoding="utf-8").splitlines()
print(mean(clip(parse(lines))))
print(list(TIMINGS))
assert list(TIMINGS) == ["parse", "clip", "mean"]
assert mean.__name__ == "mean"
Output
21.06
['parse', 'clip', 'mean']

How it works:

  1. The decorator holds the timing logic once. Each step got two lines shorter and lost a hard-coded name that could drift out of sync with the function name.
  2. func.__name__ replaces the three string keys.
  3. The finally clause adds a feature the old code lacked: a step that raises still records its time.
  4. The result 21.06 is the mean of the 40 valid readings. No reading is outside 19.0–23.0, so clip changes nothing here.

Alternative: a Timer context manager (lesson, Concepts) fits when you time a few lines inside a function rather than whole functions. Use the decorator for “every call of this function” and the context manager for “this block”.

M11-C08 · Fix the bug: the timer has no elapsed time

Section titled “M11-C08 · Fix the bug: the timer has no elapsed time”
Core

Fix the bug: this timer should report how long it takes to load data/customers.csv, but the last line fails with AttributeError: 'NoneType' object has no attribute 'elapsed'. Fix the class.

Expected output
rows: 5000
elapsed is positive: True
Starter
class Timer:
def __enter__(self):
self.start = time.perf_counter()
def __exit__(self, exc_type, exc_value, traceback):
self.elapsed = time.perf_counter() - self.start
with Timer() as t:
with open("data/customers.csv", encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f))
print("rows:", len(rows))
print("elapsed is positive:", t.elapsed > 0)
# TODO: find and fix the bug
Hint 1

The name after as receives the return value of one specific method.

Solution
class Timer:
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/customers.csv", encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f))
print("rows:", len(rows))
print("elapsed is positive:", t.elapsed > 0)
assert isinstance(t, Timer)
Output
rows: 5000
elapsed is positive: True

How it works:

  1. with Timer() as t binds t to the return value of __enter__, not to the Timer() object.
  2. The old __enter__ had no return, so t was None. The timer worked, but nobody could reach it.
  3. return self makes t the timer instance, and t.elapsed exists after the block.

Alternative: create the instance first and use it without as: timer = Timer(), with timer:, then read timer.elapsed. That works even with the bug, but every user of the class would need to know the trick. Return self.

M11-C09 · Override config thresholds temporarily

Section titled “M11-C09 · Override config thresholds temporarily”
Core

Write a generator-based context manager temporary_thresholds(config, **overrides) that changes several keys of config["thresholds"] for one block and restores all of them afterwards, even after an error. Test it on data/config.json: once normally, and once with a RuntimeError inside the block.

Expected output
inside: 1000 0.5
after: 50 0.2
after error: 1
Starter
config = json.loads(Path("data/config.json").read_text(encoding="utf-8"))
@contextmanager
def temporary_thresholds(
config: dict[str, Any], **overrides: float
) -> Iterator[dict[str, Any]]:
... # TODO: save the old values, set the overrides, yield, restore in finally
# TODO: use it with max_quantity=1000 and max_discount=0.5
# TODO: use it again with a RuntimeError inside; suppress the error outside
Hint 1

Save the old values before you change anything: old = {key: thresholds[key] for key in overrides}.

Hint 2

thresholds.update(overrides) sets the new values; thresholds.update(old) in finally restores them.

Solution
config = json.loads(Path("data/config.json").read_text(encoding="utf-8"))
@contextmanager
def temporary_thresholds(
config: dict[str, Any], **overrides: float
) -> Iterator[dict[str, Any]]:
thresholds = config["thresholds"]
old = {key: thresholds[key] for key in overrides}
thresholds.update(overrides)
try:
yield thresholds
finally:
thresholds.update(old)
before = dict(config["thresholds"])
with temporary_thresholds(config, max_quantity=1000, max_discount=0.5) as t:
print("inside:", t["max_quantity"], t["max_discount"])
thresholds = config["thresholds"]
print("after:", thresholds["max_quantity"], thresholds["max_discount"])
with suppress(RuntimeError):
with temporary_thresholds(config, min_quantity=0):
raise RuntimeError("bulk import failed")
print("after error:", config["thresholds"]["min_quantity"])
assert config["thresholds"] == before
Output
inside: 1000 0.5
after: 50 0.2
after error: 1

How it works:

  1. The old values are saved first. If a key does not exist, thresholds[key] raises a KeyError before anything changes, so a typo in an override cannot leave the config half-modified.
  2. update(overrides) applies all changes at once, and yield hands the thresholds dict to the block.
  3. The finally clause restores the old values after a normal end and after the RuntimeError.

Alternative: pandas has the same tool for display settings: with pd.option_context("display.max_rows", 5): changes options for one block and restores them (module 24).

M11-C10 · Capture the output of a chatty report function

Section titled “M11-C10 · Capture the output of a chatty report function”
Core

A legacy function prints one line per store from data/stores.csv, then a total. You cannot change it. Capture its output with redirect_stdout, keep only the North region lines and the total, and print those.

Expected output
S01 Chicago North 2850
S02 Minneapolis North 1950
S03 Detroit North 1420
total floor area: 26,230 m2
Starter
def print_store_report(path: str) -> None:
with open(path, encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f))
for row in rows:
city, region = row["city"], row["region"]
print(f"{row['store_id']} {city:<14} {region:<6} {row['size_sqm']}")
print(f"total floor area: {sum(int(r['size_sqm']) for r in rows):,} m2")
# TODO: capture the report in an io.StringIO, split it into lines,
# keep the North lines and the last line, print them
Hint 1

with redirect_stdout(buffer): print_store_report("data/stores.csv"), then buffer.getvalue().splitlines().

Hint 2

Each store line holds the region as a separate word: " North " is a safe test.

Solution
def print_store_report(path: str) -> None:
with open(path, encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f))
for row in rows:
city, region = row["city"], row["region"]
print(f"{row['store_id']} {city:<14} {region:<6} {row['size_sqm']}")
print(f"total floor area: {sum(int(r['size_sqm']) for r in rows):,} m2")
buffer = io.StringIO()
with redirect_stdout(buffer):
print_store_report("data/stores.csv")
lines = buffer.getvalue().splitlines()
north = [line for line in lines if " North " in line]
for line in [*north, lines[-1]]:
print(line)
assert len(lines) == 13
assert len(north) == 3
Output
S01 Chicago North 2850
S02 Minneapolis North 1950
S03 Detroit North 1420
total floor area: 26,230 m2

How it works:

  1. Inside the with block, print() writes to the StringIO buffer instead of the terminal. Nothing appears on screen.
  2. After the block, sys.stdout is the terminal again, and buffer.getvalue() returns everything that was printed: 12 store lines and the total.
  3. The text is now ordinary data: a list of lines to filter. The North region has 3 stores: Chicago, Minneapolis and Detroit.

Alternative: when you can change the function, return the data instead of printing it, and print in the caller. redirect_stdout is for code you do not own, such as a library that prints progress.

M11-C11 · Merge the monthly reports with ExitStack

Section titled “M11-C11 · Merge the monthly reports with ExitStack”
Core

Open all CSV files in data/reports/ at once with an ExitStack, and write them into one file output/merged.csv with the column order of the first file. Remember that 2024-04.csv has its columns in a different order. Print the number of files and rows, the header and the total revenue.

Expected output
merged 6 files, 297 rows
columns: order_id,order_date,store_id,product,category,quantity,revenue
total revenue: 57,266.39
Starter
paths = sorted(Path("data/reports").glob("*.csv"))
Path("output").mkdir(exist_ok=True)
with ExitStack() as stack:
# TODO: open every input file with stack.enter_context(open(...))
# TODO: open output/merged.csv for writing the same way
# TODO: copy the rows with csv.DictReader and csv.DictWriter
...
# TODO: read output/merged.csv back and print the summary
Hint 1

csv.DictWriter(out, fieldnames=readers[0].fieldnames) writes every row dict in the column order of the first file, whatever order the row came in.

Hint 2

Read the merged file back with csv.DictReader to count the rows and sum float(row["revenue"]).

Solution
paths = sorted(Path("data/reports").glob("*.csv"))
Path("output").mkdir(exist_ok=True)
with ExitStack() as stack:
inputs = [
stack.enter_context(open(p, encoding="utf-8", newline="")) for p in paths
]
out = stack.enter_context(
open("output/merged.csv", "w", encoding="utf-8", newline="")
)
readers = [csv.DictReader(f) for f in inputs]
writer = csv.DictWriter(out, fieldnames=readers[0].fieldnames)
writer.writeheader()
for reader in readers:
writer.writerows(reader)
with open("output/merged.csv", encoding="utf-8", newline="") as f:
merged = list(csv.DictReader(f))
header = Path("output/merged.csv").read_text(encoding="utf-8").splitlines()[0]
total = sum(float(row["revenue"]) for row in merged)
print(f"merged {len(paths)} files, {len(merged)} rows")
print("columns:", header)
print(f"total revenue: {total:,.2f}")
assert all(f.closed for f in inputs) and out.closed
assert len(merged) == 297
assert all(float(row["quantity"]) >= 1 for row in merged)
Output
merged 6 files, 297 rows
columns: order_id,order_date,store_id,product,category,quantity,revenue
total revenue: 57,266.39

How it works:

  1. enter_context opens each file and registers it for closing. The output file joins the same stack.
  2. DictReader turns each row into a dict keyed by column name. DictWriter writes the values in its own fieldnames order, so the 2024-04.csv rows land in the right columns.
  3. At the end of the block, the stack closes all 7 files in reverse order.
  4. The checks confirm 297 rows (48 + 48 + 47 + 52 + 47 + 55) and a quantity column that holds quantities, not revenues.

Alternative: with pandas, pd.concat([pd.read_csv(p) for p in paths]) aligns the columns by name in one line (module 24). For 6 small files, opening them one at a time in a loop is also fine; ExitStack matters when the files must be open together, for example to merge sorted files line by line.

M11-C12 · Count and skip only the expected errors

Section titled “M11-C12 · Count and skip only the expected errors”
Core

Write a context manager class SkipErrors(*types) that suppresses the listed exception types, counts how many it suppressed, and lets every other exception through. Use it to parse the unit_price column of data/sales_raw.csv (values such as $79.99 and "$1,299.00", plus missing tokens). Then show that a typo in a column name still raises.

Expected output
parsed 1190 prices, skipped 10
highest price: 1299.0
KeyError still raised: 'unit_prise'
Starter
class SkipErrors:
def __init__(self, *types: type[Exception]) -> None:
self.types = types
self.count = 0
# TODO: __enter__ returns self
# TODO: __exit__ counts and suppresses only self.types
with open("data/sales_raw.csv", encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f))
prices: list[float] = []
skip = SkipErrors(ValueError)
for row in rows:
with skip:
prices.append(float(row["unit_price"].replace("$", "").replace(",", "")))
# TODO: print the counts, then try the same with row["unit_prise"]
Hint 1

__exit__ returns True to suppress. Check exc_type is not None and issubclass(exc_type, self.types).

Hint 2

Increase self.count only when you suppress.

Solution
class SkipErrors:
def __init__(self, *types: type[Exception]) -> None:
self.types = types
self.count = 0
def __enter__(self) -> Self:
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: TracebackType | None,
) -> bool:
if exc_type is not None and issubclass(exc_type, self.types):
self.count += 1
return True
return False
with open("data/sales_raw.csv", encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f))
prices: list[float] = []
skip = SkipErrors(ValueError)
for row in rows:
with skip:
prices.append(float(row["unit_price"].replace("$", "").replace(",", "")))
print(f"parsed {len(prices)} prices, skipped {skip.count}")
print("highest price:", max(prices))
try:
with skip:
float(rows[0]["unit_prise"])
except KeyError as exc:
print("KeyError still raised:", exc)
assert skip.count == 10
assert len(prices) == 1190
Output
parsed 1190 prices, skipped 10
highest price: 1299.0
KeyError still raised: 'unit_prise'

How it works:

  1. For a missing token ("", N/A or -), float() raises ValueError. __exit__ sees it, counts it and returns True, so the loop continues.
  2. The 10 skipped values are exactly the 10 missing unit_price tokens in the data dictionary. Every other price, with or without a thousands separator, parses.
  3. A KeyError is not in self.types, so __exit__ returns False and the typo reaches the caller. Bugs stay visible.

Alternative: contextlib.suppress(ValueError) skips the errors but does not count them. When you need the count, a small class like this one, or an explicit try/except with a counter, is the right tool.

M11-C13 · Predict the output: nested context managers and an error

Section titled “M11-C13 · Predict the output: nested context managers and an error”
Core

Predict the output: two context managers share one with statement, and the block raises. The outer one suppresses KeyError. Write down every printed line, in order, then run the code.

Acceptance criteria:

  • You wrote every line before you ran the code.
  • Your prediction matches the Output in the solution.
  • You can explain why after prints and why rest of block does not.
Starter
@contextmanager
def step(name: str, swallow: tuple[type[Exception], ...] = ()) -> Iterator[None]:
print(f"enter {name}")
try:
yield
except swallow as exc:
print(f"{name} swallowed {type(exc).__name__}")
finally:
print(f"exit {name}")
log = []
with step("load", swallow=(KeyError,)), step("clean"):
print("in block")
log.append({"region": "North"}["store"])
print("rest of block")
print("after")
# TODO: write your prediction before you run it
Hint 1

The managers enter left to right and exit right to left. The error passes through clean first.

Hint 2

clean has an empty swallow tuple, so except () catches nothing. Its finally still runs.

Solution
@contextmanager
def step(name: str, swallow: tuple[type[Exception], ...] = ()) -> Iterator[None]:
print(f"enter {name}")
try:
yield
except swallow as exc:
print(f"{name} swallowed {type(exc).__name__}")
finally:
print(f"exit {name}")
log = []
with step("load", swallow=(KeyError,)), step("clean"):
print("in block")
log.append({"region": "North"}["store"])
print("rest of block")
print("after")
assert log == []
Output
enter load
enter clean
in block
exit clean
load swallowed KeyError
exit load
after

How it works:

  1. load enters, then clean enters, then the block prints in block.
  2. The dict lookup raises KeyError: 'store'. The rest of the block is skipped.
  3. The error reaches clean first, at its yield. except () catches nothing, so finally prints exit clean and the error continues.
  4. It reaches load next. Its except matches KeyError, prints the message, and finally prints exit load. A @contextmanager generator that catches the error and does not re-raise it suppresses it.
  5. The program continues after the with statement and prints after.

Alternative: write the managers as two nested with statements. The behavior is identical: one with with commas is short for nesting.

M11-C14 · Choose the right tool and justify it

Section titled “M11-C14 · Choose the right tool and justify it”
Core

Choose a method and justify it: for each task, choose a decorator, a context manager or a plain function. Store the choices in a dict, print them, and write one sentence of justification per task in a comment.

  1. Time every call of eight pipeline functions.
  2. Time three lines in the middle of one function.
  3. Change pandas display options for one printout, then restore them.
  4. Retry every call of an API client function.
  5. Convert a temperature from °C to °F.
  6. Open a number of files that is known only at run time.

Acceptance criteria:

  • One choice per task: "decorator", "context manager" or "plain function".
  • A one-sentence reason in a comment next to each choice.
  • Your choices match the Solution, and you can defend any difference.
Starter
choices = {
1: "...", # TODO: "decorator", "context manager" or "plain function"
}
# TODO: one comment per choice with the reason
Hint 1

Ask: does the extra behavior belong to every call of a function, or to one block of code?

Hint 2

Some tasks need no extra behavior around anything. Do not wrap what does not need wrapping.

Solution
choices = {
# Every call of a function, many functions: write @timed once, apply 8 times.
1: "decorator",
# A few lines, not a whole function: with Timer() as t: around the lines.
2: "context manager",
# Set and restore around one block: pd.option_context(...) is one.
3: "context manager",
# Behavior for every call, wherever it is called from: @retry(...).
4: "decorator",
# A pure calculation needs no setup and no cleanup.
5: "plain function",
# A variable number of resources to close together: ExitStack.
6: "context manager",
}
for task, choice in choices.items():
print(task, choice)
assert choices[1] == choices[4] == "decorator"
assert list(choices.values()).count("context manager") == 3
Output
1 decorator
2 context manager
3 context manager
4 decorator
5 plain function
6 context manager

How it works:

  1. A decorator attaches behavior to a function: every call gets it, and the call sites do not change.
  2. A context manager attaches behavior to a block: setup before, cleanup after, even on error.
  3. A plain function is the default. Use the other two only when there is a “before and after” to manage.

Alternative: some tools are both. A class based on contextlib.ContextDecorator, and every @contextmanager function, can be used as @timer() above a function or as with timer(): around a block. Challenge M11-X05 builds one.

M11-X01 · A decorator that works with and without arguments

Section titled “M11-X01 · A decorator that works with and without arguments”
Challenge

Write one decorator timed that works in both forms: @timed and @timed(label="load"). It records how many times each label ran in a Counter called RUNS (label defaults to the function name). Decorate three steps: two with a custom label and one without. Run them and print the counts.

Expected output
21.06
{'load': 2, 'parse': 2, 'stats': 2}
read_lines parse
Starter
from collections import Counter
RUNS: Counter[str] = Counter()
def timed(func=None, *, label=None):
# TODO: if func is None, the decorator was called with arguments:
# return a decorator that remembers label
# TODO: otherwise wrap func directly
...
@timed
def parse(lines: list[str]) -> list[float]: ...
@timed(label="load")
def read_lines(path: str) -> list[str]: ...
@timed(label="stats")
def mean(values: list[float]) -> float: ...
Hint 1

@timed calls timed(parse), so func is the function. @timed(label="load") calls timed(label="load"), so func is None and the result must be a decorator.

Hint 2

Write the real wrapping in an inner decorate(f). Return decorate(func) in the first case and decorate in the second.

Hint 3

The * in timed(func=None, *, label=None) makes label keyword-only, so @timed("load") cannot be confused with a function argument.

Solution
from collections import Counter
RUNS: Counter[str] = Counter()
TIMES: dict[str, float] = {}
def timed(func=None, *, label=None):
def decorate(f):
name = label or f.__name__
@functools.wraps(f)
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return f(*args, **kwargs)
finally:
TIMES[name] = time.perf_counter() - start
RUNS[name] += 1
return wrapper
if func is None:
return decorate
return decorate(func)
@timed(label="load")
def read_lines(path: str) -> list[str]:
return Path(path).read_text(encoding="utf-8").splitlines()
@timed
def parse(lines: list[str]) -> list[float]:
values = []
for line in lines:
with suppress(ValueError):
values.append(float(line))
return values
@timed(label="stats")
def mean(values: list[float]) -> float:
return round(sum(values) / len(values), 2)
for _ in range(2):
result = mean(parse(read_lines("data/readings.txt")))
print(result)
print(dict(RUNS))
print(read_lines.__name__, parse.__name__)
assert RUNS == Counter({"load": 2, "parse": 2, "stats": 2})
assert all(seconds > 0 for seconds in TIMES.values())
Output
21.06
{'load': 2, 'parse': 2, 'stats': 2}
read_lines parse

How it works:

  1. With @timed, Python calls timed(parse): func is the function, so timed wraps it at once.
  2. With @timed(label="load"), Python calls timed(label="load"): func is None, so timed returns decorate, and Python then calls decorate(read_lines).
  3. name = label or f.__name__ picks the label, or the function name when no label was given.
  4. The labels count separately from the function names, but functools.wraps still keeps the real names.

Alternative: keep two separate tools, @timed and @timed_as("load"). The dual-form decorator is convenient for users but harder to type and to read. Many libraries, such as @dataclass and @pytest.fixture, use the dual form, so you should be able to read it.

M11-X02 · A registered, validated and timed pipeline

Section titled “M11-X02 · A registered, validated and timed pipeline”
Challenge

Build a small pipeline framework. A decorator factory step(order, requires=()) registers a function in a PIPELINE list, checks that its input table (a dict of columns) has the requires columns, and records the step’s duration. run_pipeline(table) runs the registered steps sorted by order and prints one line per step with the number of columns afterwards. Use the first 500 lines of data/sales.csv as columns unit_price, quantity and discount. Register the steps out of order in the code. Finally, show that a missing column stops the run with a clear message.

Expected output
1. line_total -> 4 columns
2. flag_multi -> 5 columns
3. summary -> 7 columns
total revenue: 92311.25
multi-unit revenue: 18775.97
timed steps: ['flag_multi', 'line_total', 'summary']
stopped: step needs_revenue needs columns ['revenue']
Starter
type Table = dict[str, list[Any]]
PIPELINE: list[tuple[int, Callable[[Table], Table]]] = []
DURATIONS: dict[str, float] = {}
def step(order: int, requires: tuple[str, ...] = ()):
# TODO: decorate: build a wrapper that checks requires and records the time
# TODO: register (order, wrapper) in PIPELINE and return the wrapper
...
def run_pipeline(table: Table) -> Table:
... # TODO: run the steps sorted by order, print a line per step
# TODO: three steps: line_total (order 1), flag_multi (order 2), summary (order 3)
Hint 1

PIPELINE.append((order, wrapper)) inside decorate, then return wrapper. sorted(PIPELINE, key=lambda item: item[0]) gives the run order.

Hint 2

Each step returns a new table: {**table, "line_total": [...]}. The summary step can add one-element columns such as "total_revenue": [round(sum(...), 2)]; then the equal-length check no longer holds, so check lengths only for the requires columns.

Hint 3

For the failing run, clear PIPELINE, register one step that requires a column that does not exist, and catch the ValueError.

Solution
type Table = dict[str, list[Any]]
PIPELINE: list[tuple[int, Callable[[Table], Table]]] = []
DURATIONS: dict[str, float] = {}
def step(
order: int, requires: tuple[str, ...] = ()
) -> Callable[[Callable[[Table], Table]], Callable[[Table], Table]]:
def decorate(func: Callable[[Table], Table]) -> Callable[[Table], Table]:
@functools.wraps(func)
def wrapper(table: Table) -> Table:
missing = [name for name in requires if name not in table]
if missing:
raise ValueError(f"step {func.__name__} needs columns {missing}")
if len({len(table[name]) for name in requires}) > 1:
raise ValueError(f"step {func.__name__}: column lengths differ")
start = time.perf_counter()
try:
return func(table)
finally:
DURATIONS[func.__name__] = time.perf_counter() - start
PIPELINE.append((order, wrapper))
return wrapper
return decorate
def run_pipeline(table: Table) -> Table:
for order, func in sorted(PIPELINE, key=lambda item: item[0]):
table = func(table)
print(f"{order}. {func.__name__:<10} -> {len(table)} columns")
return table
@step(order=3, requires=("line_total", "is_multi"))
def summary(table: Table) -> Table:
multi = sum(t for t, m in zip(table["line_total"], table["is_multi"]) if m)
return {
**table,
"total_revenue": [round(sum(table["line_total"]), 2)],
"multi_unit_revenue": [round(multi, 2)],
}
@step(order=1, requires=("unit_price", "quantity", "discount"))
def line_total(table: Table) -> Table:
totals = [
round(p * q * (1 - d), 2)
for p, q, d in zip(table["unit_price"], table["quantity"], table["discount"])
]
return {**table, "line_total": totals}
@step(order=2, requires=("quantity",))
def flag_multi(table: Table) -> Table:
return {**table, "is_multi": [q >= 3 for q in table["quantity"]]}
with open("data/sales.csv", encoding="utf-8", newline="") as f:
first = [row for _, row in zip(range(500), csv.DictReader(f))]
table: Table = {
"unit_price": [float(r["unit_price"]) for r in first],
"quantity": [int(r["quantity"]) for r in first],
"discount": [float(r["discount"]) for r in first],
}
result = run_pipeline(table)
print("total revenue:", result["total_revenue"][0])
print("multi-unit revenue:", result["multi_unit_revenue"][0])
print("timed steps:", sorted(DURATIONS))
PIPELINE.clear()
@step(order=1, requires=("revenue",))
def needs_revenue(table: Table) -> Table:
return table
try:
run_pipeline(table)
except ValueError as exc:
print("stopped:", exc)
expected_total = round(sum(float(r["revenue"]) for r in first), 2)
# a few lines differ by a cent from the file's rounding (see the data dictionary)
assert math.isclose(result["total_revenue"][0], expected_total, abs_tol=0.10)
assert list(DURATIONS) == ["line_total", "flag_multi", "summary"]
Output
1. line_total -> 4 columns
2. flag_multi -> 5 columns
3. summary -> 7 columns
total revenue: 92311.25
multi-unit revenue: 18775.97
timed steps: ['flag_multi', 'line_total', 'summary']
stopped: step needs_revenue needs columns ['revenue']

How it works:

  1. Each @step(...) line registers the wrapped function with its order when the module loads. The code defines summary first, but run_pipeline sorts by order, so it runs third.
  2. The wrapper checks the required columns before the step runs, and times only the step body.
  3. Each step returns a new dict with extra columns. The input table is never changed.
  4. The total is within a few cents of the sum of the revenue column for the same 500 lines. Each line can differ by one cent, because the file was rounded with NumPy and the step rounds with Python’s round().
  5. In the failing run, the check stops the pipeline before any work, and the message names the step and the column.

Alternative: frameworks such as Prefect, Dagster and Airflow use exactly this design: @task or @asset decorators register functions, and a runner orders and instruments them.

Challenge

An exchange-rate API changes its answer every few minutes, so a plain cache would return stale rates forever. Write a decorator factory ttl_cache(seconds, clock=time.monotonic): it caches results by their arguments and recomputes an entry once it is older than seconds. TTL means “time to live”. Test it with a fake clock (a list you change by hand) and a fake rate function that counts its calls.

Expected output
t= 0.0s EUR=0.93 calls=1
t=30.0s EUR=0.93 calls=1
t=59.9s EUR=0.93 calls=1
t=61.0s EUR=0.94 calls=2
t=90.0s EUR=0.94 calls=2
GBP: 0.82 calls: 3
Starter
def ttl_cache(seconds: float, clock: Callable[[], float] = time.monotonic):
# TODO: store (value, time stored) per argument tuple
# TODO: recompute when clock() - stored_at >= seconds
...
now = [0.0] # the fake clock reads now[0]
calls: list[str] = []
@ttl_cache(seconds=60, clock=lambda: now[0])
def usd_rate(currency: str) -> float:
calls.append(currency)
return round({"EUR": 0.92, "GBP": 0.79}[currency] + 0.01 * len(calls), 2)
# TODO: for t in [0.0, 30.0, 59.9, 61.0, 90.0]: set now[0] = t, call usd_rate("EUR")
# and print f"t={t:>4}s EUR={...} calls={len(calls)}"
# TODO: at t = 95.0, print the GBP rate and the number of calls
Hint 1

The cache is a dict: key args, value (result, stored_at).

Hint 2

time.monotonic() is a clock that never goes backwards. It suits expiry checks better than time.time(). The fake clock replaces it in tests.

Solution
def ttl_cache[R](
seconds: float, clock: Callable[[], float] = time.monotonic
) -> Callable[[Callable[..., R]], Callable[..., R]]:
def decorate(func: Callable[..., R]) -> Callable[..., R]:
cache: dict[tuple, tuple[R, float]] = {}
@functools.wraps(func)
def wrapper(*args: Any) -> R:
entry = cache.get(args)
if entry is not None and clock() - entry[1] < seconds:
return entry[0]
value = func(*args)
cache[args] = (value, clock())
return value
return wrapper
return decorate
now = [0.0] # the fake clock reads now[0]
calls: list[str] = []
@ttl_cache(seconds=60, clock=lambda: now[0])
def usd_rate(currency: str) -> float:
calls.append(currency)
return round({"EUR": 0.92, "GBP": 0.79}[currency] + 0.01 * len(calls), 2)
for t in [0.0, 30.0, 59.9, 61.0, 90.0]:
now[0] = t
print(f"t={t:>4}s EUR={usd_rate('EUR')} calls={len(calls)}")
now[0] = 95.0
print("GBP:", usd_rate("GBP"), "calls:", len(calls))
assert calls == ["EUR", "EUR", "GBP"]
Output
t= 0.0s EUR=0.93 calls=1
t=30.0s EUR=0.93 calls=1
t=59.9s EUR=0.93 calls=1
t=61.0s EUR=0.94 calls=2
t=90.0s EUR=0.94 calls=2
GBP: 0.82 calls: 3

How it works:

  1. At t = 0 the cache is empty: one real call, stored with time 0.
  2. At t = 30 and t = 59.9 the entry is younger than 60 seconds: cache hits, no new calls.
  3. At t = 61 the entry is too old: a second real call returns a new rate, stored with time 61. At t = 90 it is 29 seconds old, so it is a hit again.
  4. GBP has its own key, so its first lookup is a real call.
  5. The injected clock makes the test exact and instant, like the injected sleep of the retry decorator.

Alternative: the third-party cachetools library has a ready TTLCache and a @cached(cache=TTLCache(maxsize=..., ttl=60)) decorator. HTTP clients often honor the server’s own cache headers instead.

Challenge

A job overwrites region_report.csv every night. If it crashes halfway, the file must keep yesterday’s complete content, never a half-written one. Write a context manager atomic_write(path) that yields a file object for a temporary file in the same folder. On success it replaces the target with os.replace(). On error it deletes the temporary file and re-raises. Test it inside a temporary folder: a successful write, then a write that crashes after one row.

Expected output
v1: ['East,426330.93', 'North,377689.94']
crash: could not convert string to float: 'broken'
after crash: ['East,426330.93', 'North,377689.94']
files: ['region_report.csv']
Starter
@contextmanager
def atomic_write(path: str | Path) -> Iterator[io.TextIOWrapper]:
target = Path(path)
tmp = target.with_name(target.name + ".tmp")
# TODO: open tmp for writing, yield it
# TODO: on success: close it, then os.replace(tmp, target)
# TODO: on error: close it, delete tmp, re-raise
...
with tempfile.TemporaryDirectory() as folder, chdir(folder):
... # TODO: write version 1, then a version 2 that raises halfway
Hint 1

Use try: yield f with except BaseException: for the error path (delete and raise), and else: for the success path (replace).

Hint 2

Close the file before you replace or delete it. A with open(...) around the try does that for you.

Hint 3

os.replace() is atomic on the same file system: other programs see either the old file or the new file, never a mix. That is why the temporary file goes in the same folder.

Solution
@contextmanager
def atomic_write(path: str | Path) -> Iterator[io.TextIOWrapper]:
target = Path(path)
tmp = target.with_name(target.name + ".tmp")
try:
with open(tmp, "w", encoding="utf-8", newline="") as f:
yield f
except BaseException:
tmp.unlink(missing_ok=True)
raise
os.replace(tmp, target)
rows_v1 = [("East", 426330.93), ("North", 377689.94)]
rows_v2 = [("East", 430000.00), ("North", "broken")]
with tempfile.TemporaryDirectory() as folder, chdir(folder):
with atomic_write("region_report.csv") as f:
csv.writer(f).writerows(rows_v1)
print("v1:", Path("region_report.csv").read_text(encoding="utf-8").splitlines())
try:
with atomic_write("region_report.csv") as f:
writer = csv.writer(f)
for region, revenue in rows_v2:
writer.writerow([region, f"{float(revenue):.2f}"])
except ValueError as exc:
print("crash:", exc)
content = Path("region_report.csv").read_text(encoding="utf-8").splitlines()
print("after crash:", content)
print("files:", sorted(os.listdir(".")))
assert content == ["East,426330.93", "North,377689.94"]
Output
v1: ['East,426330.93', 'North,377689.94']
crash: could not convert string to float: 'broken'
after crash: ['East,426330.93', 'North,377689.94']
files: ['region_report.csv']

How it works:

  1. All writes go to region_report.csv.tmp. The real file is untouched while the block runs.
  2. On success, the inner with closes the temporary file, and os.replace() swaps it in for the target in one step.
  3. On the crash, the float("broken") error reappears at yield. The inner with closes the file, the except deletes it and raise passes the error on. The target still holds version 1.
  4. The folder holds only the report afterwards: no stray .tmp file.

Alternative: tempfile.NamedTemporaryFile(dir=target.parent, delete=False) creates a temporary file with a unique random name, which avoids clashes when two jobs write at once. The fixed .tmp name keeps this solution easy to read.

M11-X05 · One stopwatch for decorators and with blocks

Section titled “M11-X05 · One stopwatch for decorators and with blocks”
Challenge

Refactor procedural code into a class. A script times its steps with loose variables (start_load, start_clean, …) and a list of laps. Write a class Stopwatch based on contextlib.ContextDecorator that records a lap (label, seconds) each time a block or a decorated function finishes. One instance must work both as @watch above a function and as with watch: around a block. Print the lap labels.

Expected output
{'North': 6220, 'South': 7080, 'East': 7210, 'West': 5720}
3 laps: ['stores', 'stores', 'stores']
True
Starter
from contextlib import ContextDecorator
# Before: procedural timing
# start_load = time.perf_counter(); rows = load(); laps.append(("load", ...))
# start_clean = time.perf_counter(); ...
class Stopwatch(ContextDecorator):
def __init__(self, label: str, laps: list[tuple[str, float]]) -> None:
... # TODO: store the label and the shared list of laps
# TODO: __enter__ starts the clock, __exit__ appends (label, seconds)
# TODO: create one instance watch = Stopwatch("stores", laps)
# TODO: use it as @watch above a load function and as with watch: around a block
Hint 1

ContextDecorator adds a __call__ method: @watch wraps the function so that every call runs inside with watch:.

Hint 2

In __exit__, compute the duration and append (self.label, seconds) to self.laps. Return None, so that an error in the timed code still reaches the caller.

Solution
from contextlib import ContextDecorator
class Stopwatch(ContextDecorator):
"""Record (label, seconds) for every block or decorated call."""
def __init__(self, label: str, laps: list[tuple[str, float]]) -> None:
self.label = label
self.laps = laps
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.laps.append((self.label, time.perf_counter() - self.start))
laps: list[tuple[str, float]] = []
watch = Stopwatch("stores", laps) # one instance, used two ways
@watch
def load_stores(path: str) -> list[dict[str, str]]:
with open(path, encoding="utf-8", newline="") as f:
return list(csv.DictReader(f))
stores = load_stores("data/stores.csv")
stores = load_stores("data/stores.csv")
with watch:
by_region: dict[str, int] = {}
for s in stores:
by_region[s["region"]] = by_region.get(s["region"], 0) + int(s["size_sqm"])
print(by_region)
print(len(laps), "laps:", [label for label, _ in laps])
print(all(seconds > 0 for _, seconds in laps))
assert len(laps) == 3 and {label for label, _ in laps} == {"stores"}
Output
{'North': 6220, 'South': 7080, 'East': 7210, 'West': 5720}
3 laps: ['stores', 'stores', 'stores']
True

How it works:

  1. The class is a normal context manager: __enter__ starts the clock and __exit__ appends a lap.
  2. ContextDecorator adds the decorator side. @watch wraps load_stores so that each call runs inside with watch:: two calls, two laps.
  3. The same object then times a block with with watch:, which adds the third lap. One instance, both uses.
  4. One instance works here because the uses come one after another. self.start is shared, so nested or parallel use of the same instance would overwrite it; create one instance per concurrent use.
  5. The loose start_* variables of the procedural script are gone. Each timing is one line, and all laps share one list.

Alternative: a @contextmanager function is a ContextDecorator too. @contextmanager def stopwatch(label, laps): ... can also be used as @stopwatch("load", laps), as long as each use creates a new one.

M11-X06 · Give up with a clear error and the full history

Section titled “M11-X06 · Give up with a clear error and the full history”
Challenge

When a retry decorator gives up, the caller sees only the last error. Write retry_with_history(attempts, delays, sleep). As in M11-C04 and data/config.json, attempts is the total number of calls, and the decorator waits delays[k - 1] before retry k. After the last failed attempt it raises a custom RetryError that says how many attempts failed and keeps the list of all errors in an attribute errors. Chain the last error with raise ... from ... so the traceback shows it. Test it with a fake fetch that fails with a different error message each time and never succeeds.

Expected output
fetch_forecast failed 4 times
ConnectionError - attempt 1: weather API unavailable
TimeoutError - attempt 2: weather API unavailable
ConnectionError - attempt 3: weather API unavailable
TimeoutError - attempt 4: weather API unavailable
cause: TimeoutError('attempt 4: weather API unavailable')
waits: [1, 2, 4]
Starter
class RetryError(Exception):
def __init__(self, message: str, errors: list[Exception]) -> None:
super().__init__(message)
self.errors = errors
def retry_with_history(attempts: int, delays: Sequence[float], sleep=time.sleep):
... # TODO: collect each error; after the last one raise RetryError(...) from it
# TODO: a fetch that never succeeds: odd attempts raise ConnectionError,
# even attempts raise TimeoutError, both with f"attempt {n}: ..."
# TODO: catch RetryError, print its message, the errors and __cause__
Hint 1

Loop for attempt in range(1, attempts + 1):. After a failure, sleep delays[attempt - 1], except after the last attempt.

Hint 2

raise RetryError(msg, errors) from errors[-1] sets __cause__. The traceback then prints “The above exception was the direct cause of the following exception”.

Solution
class RetryError(Exception):
"""Raised when every attempt failed. `errors` holds them all, in order."""
def __init__(self, message: str, errors: list[Exception]) -> None:
super().__init__(message)
self.errors = errors
def retry_with_history[**P, R](
attempts: int,
delays: Sequence[float],
sleep: Callable[[float], object] = time.sleep,
) -> Callable[[Callable[P, R]], Callable[P, R]]:
def decorate(func: Callable[P, R]) -> Callable[P, R]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
errors: list[Exception] = []
for attempt in range(1, attempts + 1):
try:
return func(*args, **kwargs)
except (ConnectionError, TimeoutError) as exc:
errors.append(exc)
if attempt < attempts:
sleep(delays[attempt - 1])
message = f"{func.__name__} failed {len(errors)} times"
raise RetryError(message, errors) from errors[-1]
return wrapper
return decorate
waits: list[float] = []
attempts = 0
@retry_with_history(4, [1, 2, 4], sleep=waits.append)
def fetch_forecast(path: str) -> dict[str, Any]:
global attempts
attempts += 1
kind = ConnectionError if attempts % 2 else TimeoutError
raise kind(f"attempt {attempts}: weather API unavailable")
try:
fetch_forecast("data/api/weather_forecast.json")
except RetryError as exc:
print(exc)
for error in exc.errors:
print(" ", type(error).__name__, "-", error)
print("cause:", repr(exc.__cause__))
print("waits:", waits)
history = exc.errors
assert len(history) == 4 and waits == [1, 2, 4]
Output
fetch_forecast failed 4 times
ConnectionError - attempt 1: weather API unavailable
TimeoutError - attempt 2: weather API unavailable
ConnectionError - attempt 3: weather API unavailable
TimeoutError - attempt 4: weather API unavailable
cause: TimeoutError('attempt 4: weather API unavailable')
waits: [1, 2, 4]

How it works:

  1. Each failure is appended to errors. The function sleeps after the first three failures, but not after the last one: waiting before giving up wastes time.
  2. After the loop, RetryError carries a summary message and the full error list. The caller can log every attempt, not just the last.
  3. from errors[-1] stores the last error as __cause__. An uncaught RetryError would print both tracebacks, linked by “The above exception was the direct cause of the following exception”.
  4. The fake fetch alternates between ConnectionError and TimeoutError, so the history shows both types.

Alternative: Python 3.11+ has ExceptionGroup, which bundles several exceptions into one: raise ExceptionGroup("fetch failed", errors). Callers can handle it with except*. It is the standard choice when several independent errors happen together, for example in parallel tasks; a custom RetryError reads better for one function that failed several times.