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:
- Read the task and the expected output.
- Copy the setup block and the starter code into a script, and replace each to-do comment with your code.
- Run the script from your project folder. Compare your output with the expected output.
- 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 csvimport functoolsimport inspectimport ioimport jsonimport mathimport osimport tempfileimport timefrom collections.abc import Callable, Iterator, Sequencefrom contextlib import ExitStack, chdir, contextmanager, redirect_stdout, suppressfrom pathlib import Pathfrom types import TracebackTypefrom typing import Any, SelfWarm-up
Section titled “Warm-up”M11-W01 · Run cleaning steps named in a config
Section titled “M11-W01 · Run cleaning steps named in a config”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.
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]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 orderHint 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 = rawfor 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())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:
- Each step is a normal function. The dict stores the function objects, not their results.
- The loop looks up each configured name and calls the function it finds.
step.__name__comes from the function object itself, so the report always matches the code.values: Anytells 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”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.
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")
@registerdef load(): return 3
@registerdef clean(n): return n - 1
print("defined")print(clean(load()))# TODO: write your prediction for each line before you run itHint 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")
@registerdef load(): return 3
@registerdef clean(n): return n - 1
print("defined")print(clean(load()))assert clean.__name__ == "wrapper"startregister loadregister cleandefinedcall loadcall clean2How it works:
startprints first, because it is the first statement.- Each
@registerline runs the decorator body once, when itsdefexecutes. Soregister loadandregister cleanprint beforedefined. clean(load())evaluates the inner call first: theloadwrapper printscall loadand returns 3. Then thecleanwrapper printscall cleanand returns 2.- The assert shows a side effect: without
functools.wraps, the decoratedcleanis namedwrapper.
Alternative: add @functools.wraps(func) to the wrapper. The output stays the same, and clean.__name__ becomes 'clean'.
M11-W03 · Write a call-logging decorator
Section titled “M11-W03 · Write a call-logging decorator”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.
call scale args=([1.0, 2.5],) kwargs={'factor': 2}[2.0, 5.0]scaledef 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_callsdef 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_callsdef 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"call scale args=([1.0, 2.5],) kwargs={'factor': 2}[2.0, 5.0]scaleHow it works:
*argscollects the positional arguments into a tuple: one list here, so([1.0, 2.5],)with a trailing comma.**kwargscollects the keyword arguments into a dict:{'factor': 2}.func(*args, **kwargs)unpacks both again, soscalereceives exactly what the caller passed.functools.wrapscopies the name, soscale.__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”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.
computing mean_price542.66def log_calls(func): @functools.wraps(func) def wrapper(*args, **kwargs): print(f"computing {func.__name__}") func(*args, **kwargs)
return wrapper
@log_callsdef 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 bugHint 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_callsdef 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.66computing mean_price542.66How it works:
- The wrapper called
funcbut did not return its value. A function withoutreturnreturnsNone. - Adding
returnpasses the original result back to the caller. - 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”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.
['drop_returns', 'cap_bulk']Remove lines with quantity <= 0.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_emptydef drop_returns(quantities: list[int]) -> list[int]: """Remove lines with quantity <= 0.""" return [q for q in quantities if q > 0]
@check_not_emptydef 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 decoratorHint 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_emptydef drop_returns(quantities: list[int]) -> list[int]: """Remove lines with quantity <= 0.""" return [q for q in quantities if q > 0]
@check_not_emptydef 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]['drop_returns', 'cap_bulk']Remove lines with quantity <= 0.How it works:
- Without
wraps, each decorated name refers to a function calledwrapper, with no docstring. @functools.wraps(func)copies__name__,__doc__and the other metadata fromfunc.- 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”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.
== Store S01 (Chicago) ==orders: 3revenue: 458.94== end Store S01 (Chicago) ==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== Store S01 (Chicago) ==orders: 3revenue: 458.94== end Store S01 (Chicago) ==How it works:
with Section(...)creates the instance and calls its__enter__, which prints the header and returns the instance foras section.- The block body runs.
__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”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.
40 valid readings, mean 21.06 °Creadings: 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 meanHint 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) == 40assert 19.3 <= min(readings) and max(readings) <= 22.940 valid readings, mean 21.06 °CHow it works:
float()ignores the line break at the end of each line, and raisesValueErrorforerror,""andn/a.suppress(ValueError)ends that iteration’swithblock quietly. Theappendnever runs for a bad line.- 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”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.
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 itHint 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))"round(clip(0.87))clip(round(0.87))How it works:
- The bottom decorator wraps first. For
score,clipwraps the function, thenroundwraps theclipwrapper. - At call time, the
roundwrapper calls theclipwrapper, which callsscore. Theclipwrapper returnsclip(0.87), and theroundwrapper wraps that inround(...). - 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”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.
checked 1200 lines, 1190 validcalls: 1200rejected: [-3, -2, -2, -2, -1, -1, 250, 500, 999, 1000]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_callsdef 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 countHint 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_callsdef 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) == 1200assert len(valid) == 1190checked 1200 lines, 1190 validcalls: 1200rejected: [-3, -2, -2, -2, -1, -1, 250, 500, 999, 1000]How it works:
wrapper.calls = 0stores the counter on the wrapper object. The decorator returns that same object, sois_valid_quantity.callsreads it.- Each call adds 1 before it forwards the arguments.
sales_raw.csvhas 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”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.
churn rate: 19.26%load_customers: 3 runs, all positive: Truechurn_rate: 3 runs, all positive: Truedef 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 reportHint 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}churn rate: 19.26%load_customers: 3 runs, all positive: Truechurn_rate: 3 runs, all positive: TrueHow it works:
timed(RUNS)runs first and returnsdecorate, which wraps the step. Each step gets its own wrapper, but both write into the same registry.setdefaultreturns the existing list for a name, or stores and returns a new empty one.- The
finallyclause records a duration on success and on failure. row["churned"] == "1"is abool, andsum()countsTrueas 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”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.
mean monthly charges: 60.84churn rate: 0.193Average monthly charge per customer, in USD.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.193assert mean_monthly_charges.__name__ == "mean_monthly_charges"mean monthly charges: 60.84churn rate: 0.193Average monthly charge per customer, in USD.How it works:
- The factory takes
digitsand returnsdecorate.decoratetakes the metric and returnswrapper.wrappercomputes and rounds. - Each
@round_result(...)line creates a separatedecoratewith its owndigits. - The hints use only
**P: the return type is alwaysfloat, so noRis needed. - 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”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.
page 2 of 3first product: P011 Waterproof Rain Jacketwaits: [0.5, 1.0, 2.0]gave up: attempt 3 timed out | waits: [0.5, 1.0]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 waitsHint 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]page 2 of 3first product: P011 Waterproof Rain Jacketwaits: [0.5, 1.0, 2.0]gave up: attempt 3 timed out | waits: [0.5, 1.0]How it works:
- The loop makes up to
attemptscalls. A success returns at once. - A listed exception on attempt
kwaitsbase_delay * 2**k: 0.5, 1.0 and 2.0 seconds fork= 0, 1, 2. - On the last attempt, the bare
raisere-raises the same exception, so the caller sees the real error. - The final
raise AssertionError("unreachable")runs only forattempts=0, which makes no sense. It also tells a type checker that the function cannot end without returning a value. - The second test fails every time: 3 attempts, 2 waits, then the original
TimeoutErrorreaches 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”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.
[0.769, 0.5, 0.047]rejected: churn_score_raw returned 1.2 at index 0def check_probabilities(func): ... # TODO: call func, check each value is in [0, 1], else raise ValueError
@check_probabilitiesdef 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_probabilitiesdef 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 errorHint 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_probabilitiesdef 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_probabilitiesdef 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"[0.769, 0.5, 0.047]rejected: churn_score_raw returned 1.2 at index 0How it works:
- The wrapper calls the scorer first, then checks the result. This is an output validator: it guards the caller from a broken function.
- The logistic function always gives a value between 0 and 1, so
churn_scorepasses. Short tenure gives a high churn risk, as indata/customers.csv. churn_score_rawreturns1.5 - 0.15 * 2 = 1.2for 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”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.
uncached file reads: 1000cached file reads: 11CacheInfo(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-25first S12 sale: 2023-06-15reads: 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 S12Hint 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_cachedassert len(reads) == cached_city.cache_info().misses == 11assert s12_first > dates[-1]uncached file reads: 1000cached file reads: 11CacheInfo(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-25first S12 sale: 2023-06-15How it works:
- Without the cache, every line opens the file: 1,000 reads.
- With
functools.cache, the first lookup of each store id is a miss that reads the file. Every later lookup is a hit. - 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. maxsize=Nonein the statistics means the cache has no size limit, which is whatfunctools.cacheis.
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”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.
21.06['parse', 'clip', 'mean']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 stepsHint 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
@timeddef parse(lines: list[str]) -> list[float]: values = [] for line in lines: with suppress(ValueError): values.append(float(line)) return values
@timeddef clip(values: list[float]) -> list[float]: return [min(max(v, 19.0), 23.0) for v in values]
@timeddef 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"21.06['parse', 'clip', 'mean']How it works:
- 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.
func.__name__replaces the three string keys.- The
finallyclause adds a feature the old code lacked: a step that raises still records its time. - The result 21.06 is the mean of the 40 valid readings. No reading is outside 19.0–23.0, so
clipchanges 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”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.
rows: 5000elapsed is positive: Trueclass 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 bugHint 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)rows: 5000elapsed is positive: TrueHow it works:
with Timer() as tbindstto the return value of__enter__, not to theTimer()object.- The old
__enter__had noreturn, sotwasNone. The timer worked, but nobody could reach it. return selfmakestthe timer instance, andt.elapsedexists 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”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.
inside: 1000 0.5after: 50 0.2after error: 1config = json.loads(Path("data/config.json").read_text(encoding="utf-8"))
@contextmanagerdef 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 outsideHint 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"))
@contextmanagerdef 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"] == beforeinside: 1000 0.5after: 50 0.2after error: 1How it works:
- The old values are saved first. If a key does not exist,
thresholds[key]raises aKeyErrorbefore anything changes, so a typo in an override cannot leave the config half-modified. update(overrides)applies all changes at once, andyieldhands the thresholds dict to the block.- The
finallyclause restores the old values after a normal end and after theRuntimeError.
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”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.
S01 Chicago North 2850S02 Minneapolis North 1950S03 Detroit North 1420total floor area: 26,230 m2def 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 themHint 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) == 13assert len(north) == 3S01 Chicago North 2850S02 Minneapolis North 1950S03 Detroit North 1420total floor area: 26,230 m2How it works:
- Inside the
withblock,print()writes to theStringIObuffer instead of the terminal. Nothing appears on screen. - After the block,
sys.stdoutis the terminal again, andbuffer.getvalue()returns everything that was printed: 12 store lines and the total. - 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”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.
merged 6 files, 297 rowscolumns: order_id,order_date,store_id,product,category,quantity,revenuetotal revenue: 57,266.39paths = 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 summaryHint 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.closedassert len(merged) == 297assert all(float(row["quantity"]) >= 1 for row in merged)merged 6 files, 297 rowscolumns: order_id,order_date,store_id,product,category,quantity,revenuetotal revenue: 57,266.39How it works:
enter_contextopens each file and registers it for closing. The output file joins the same stack.DictReaderturns each row into a dict keyed by column name.DictWriterwrites the values in its ownfieldnamesorder, so the2024-04.csvrows land in the right columns.- At the end of the block, the stack closes all 7 files in reverse order.
- The checks confirm 297 rows (48 + 48 + 47 + 52 + 47 + 55) and a
quantitycolumn 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”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.
parsed 1190 prices, skipped 10highest price: 1299.0KeyError still raised: 'unit_prise'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 == 10assert len(prices) == 1190parsed 1190 prices, skipped 10highest price: 1299.0KeyError still raised: 'unit_prise'How it works:
- For a missing token (
"",N/Aor-),float()raisesValueError.__exit__sees it, counts it and returnsTrue, so the loop continues. - The 10 skipped values are exactly the 10 missing
unit_pricetokens in the data dictionary. Every other price, with or without a thousands separator, parses. - A
KeyErroris not inself.types, so__exit__returnsFalseand 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”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
afterprints and whyrest of blockdoes not.
@contextmanagerdef 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 itHint 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
@contextmanagerdef 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 == []enter loadenter cleanin blockexit cleanload swallowed KeyErrorexit loadafterHow it works:
loadenters, thencleanenters, then the block printsin block.- The dict lookup raises
KeyError: 'store'. The rest of the block is skipped. - The error reaches
cleanfirst, at itsyield.except ()catches nothing, sofinallyprintsexit cleanand the error continues. - It reaches
loadnext. ItsexceptmatchesKeyError, prints the message, andfinallyprintsexit load. A@contextmanagergenerator that catches the error and does not re-raise it suppresses it. - The program continues after the
withstatement and printsafter.
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”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.
- Time every call of eight pipeline functions.
- Time three lines in the middle of one function.
- Change pandas display options for one printout, then restore them.
- Retry every call of an API client function.
- Convert a temperature from °C to °F.
- 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.
choices = { 1: "...", # TODO: "decorator", "context manager" or "plain function"}# TODO: one comment per choice with the reasonHint 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") == 31 decorator2 context manager3 context manager4 decorator5 plain function6 context managerHow it works:
- A decorator attaches behavior to a function: every call gets it, and the call sites do not change.
- A context manager attaches behavior to a block: setup before, cleanup after, even on error.
- 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.
Challenge
Section titled “Challenge”M11-X01 · A decorator that works with and without arguments
Section titled “M11-X01 · A decorator that works with and without arguments”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.
21.06{'load': 2, 'parse': 2, 'stats': 2}read_lines parsefrom 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 ...
@timeddef 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()
@timeddef 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())21.06{'load': 2, 'parse': 2, 'stats': 2}read_lines parseHow it works:
- With
@timed, Python callstimed(parse):funcis the function, sotimedwraps it at once. - With
@timed(label="load"), Python callstimed(label="load"):funcisNone, sotimedreturnsdecorate, and Python then callsdecorate(read_lines). name = label or f.__name__picks the label, or the function name when no label was given.- The labels count separately from the function names, but
functools.wrapsstill 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”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.
1. line_total -> 4 columns2. flag_multi -> 5 columns3. summary -> 7 columnstotal revenue: 92311.25multi-unit revenue: 18775.97timed steps: ['flag_multi', 'line_total', 'summary']stopped: step needs_revenue needs columns ['revenue']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"]1. line_total -> 4 columns2. flag_multi -> 5 columns3. summary -> 7 columnstotal revenue: 92311.25multi-unit revenue: 18775.97timed steps: ['flag_multi', 'line_total', 'summary']stopped: step needs_revenue needs columns ['revenue']How it works:
- Each
@step(...)line registers the wrapped function with its order when the module loads. The code definessummaryfirst, butrun_pipelinesorts byorder, so it runs third. - The wrapper checks the required columns before the step runs, and times only the step body.
- Each step returns a new dict with extra columns. The input table is never changed.
- The total is within a few cents of the sum of the
revenuecolumn 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’sround(). - 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.
M11-X03 · A cache whose entries expire
Section titled “M11-X03 · A cache whose entries expire”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.
t= 0.0s EUR=0.93 calls=1t=30.0s EUR=0.93 calls=1t=59.9s EUR=0.93 calls=1t=61.0s EUR=0.94 calls=2t=90.0s EUR=0.94 calls=2GBP: 0.82 calls: 3def 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 callsHint 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.0print("GBP:", usd_rate("GBP"), "calls:", len(calls))assert calls == ["EUR", "EUR", "GBP"]t= 0.0s EUR=0.93 calls=1t=30.0s EUR=0.93 calls=1t=59.9s EUR=0.93 calls=1t=61.0s EUR=0.94 calls=2t=90.0s EUR=0.94 calls=2GBP: 0.82 calls: 3How it works:
- At t = 0 the cache is empty: one real call, stored with time 0.
- At t = 30 and t = 59.9 the entry is younger than 60 seconds: cache hits, no new calls.
- 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.
- GBP has its own key, so its first lookup is a real call.
- The injected clock makes the test exact and instant, like the injected
sleepof 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.
M11-X04 · Write a report file atomically
Section titled “M11-X04 · Write a report file atomically”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.
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']@contextmanagerdef 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 halfwayHint 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
@contextmanagerdef 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"]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:
- All writes go to
region_report.csv.tmp. The real file is untouched while the block runs. - On success, the inner
withcloses the temporary file, andos.replace()swaps it in for the target in one step. - On the crash, the
float("broken")error reappears atyield. The innerwithcloses the file, theexceptdeletes it andraisepasses the error on. The target still holds version 1. - The folder holds only the report afterwards: no stray
.tmpfile.
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”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.
{'North': 6220, 'South': 7080, 'East': 7210, 'West': 5720}3 laps: ['stores', 'stores', 'stores']Truefrom 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 blockHint 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
@watchdef 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"}{'North': 6220, 'South': 7080, 'East': 7210, 'West': 5720}3 laps: ['stores', 'stores', 'stores']TrueHow it works:
- The class is a normal context manager:
__enter__starts the clock and__exit__appends a lap. ContextDecoratoradds the decorator side.@watchwrapsload_storesso that each call runs insidewith watch:: two calls, two laps.- The same object then times a block with
with watch:, which adds the third lap. One instance, both uses. - One instance works here because the uses come one after another.
self.startis shared, so nested or parallel use of the same instance would overwrite it; create one instance per concurrent use. - 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”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.
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 unavailablecause: TimeoutError('attempt 4: weather API unavailable')waits: [1, 2, 4]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.errorsassert len(history) == 4 and waits == [1, 2, 4]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 unavailablecause: TimeoutError('attempt 4: weather API unavailable')waits: [1, 2, 4]How it works:
- 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. - After the loop,
RetryErrorcarries a summary message and the full error list. The caller can log every attempt, not just the last. from errors[-1]stores the last error as__cause__. An uncaughtRetryErrorwould print both tracebacks, linked by “The above exception was the direct cause of the following exception”.- The fake fetch alternates between
ConnectionErrorandTimeoutError, 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.