Skip to content

Part 2 checkpoint

This checkpoint tests Part 2 as a whole. Each exercise mixes two to four modules, as real work does: you stream a file through generators, wrap the steps in a decorator, type the records, test the result, and pick the data structure that keeps it fast. The exercises use the course datasets in data/ and are new: they combine the skills in tasks that the module exercises and mini-projects do not ask.

How to use it:

  1. Work without your notes first. Read the task and the expected output, then write your code.
  2. Stuck for more than 10 minutes? Open one hint at a time.
  3. Open the solution only after a real attempt. Compare your code with it, not only your output.
  4. Score yourself with the rubric at the end of the page.

Plan about 7 to 11 hours in total: 15–20 minutes for each of the 3 warm-ups, 30–45 minutes for each of the 8 core exercises and 45–75 minutes for each of the 3 challenges. You can split the work over several sessions.

Exercise Tier Type Modules
P2-01 Warm-up Predict the output 10, 11, 13
P2-02 Warm-up Fix the bugs 10, 12, 13
P2-03 Warm-up Fix the bugs 10, 12, 13
P2-04 Core Write the code 10, 11, 12
P2-05 Core Write the code 10, 12, 16, 17
P2-06 Core Write the code and the tests 12, 14, 16
P2-07 Core Interpret and refactor 11, 13, 15, 17
P2-08 Core Fix the bugs 12, 15, 16
P2-09 Core Write the code 10, 13, 17
P2-10 Core Fix the bugs (mypy) 12, 13, 17
P2-11 Core Choose and justify 11, 13, 15, 17
P2-12 Challenge Predict, then rewrite 10, 11
P2-13 Challenge Write the code 11, 12, 15, 16
P2-14 Challenge Write the code 10, 13, 15, 17

Work in your course project folder with Python 3.12 or newer and the virtual environment of the course. The data/ folder from Get the data must be in that folder, because every path on this page is relative to it (data/sales.csv). The data dictionary lists the facts you can check your results against. Run each exercise as its own script, for example python p2_04.py. Scripts that write files write to output/, never into data/.

The exercises use the standard library plus httpx, beautifulsoup4, pytest, pytest-cov and mypy, all in the course requirements. No exercise uses the network: the API exercises replace it with httpx.MockTransport and the saved responses in data/api/.

Each solution ends with assert checks. Add the same checks to your own code: a silent run means that every check passed.

P2-01 · Predict the output: a lazy filter behind a decorator

Section titled “P2-01 · Predict the output: a lazy filter behind a decorator”
Warm-up

Predict the output: announce decorates a generator function that filters sensor temperatures, and two small lambdas check a limit. Write down every line that the script prints, in order, then run it.

Acceptance criteria:

  • Write your prediction for all 14 lines before you run the code.
  • Your prediction matches the Output in the solution, line by line.
  • For each line you got wrong, you can name the rule and the module that explains it.
Starter
from collections.abc import Callable, Iterator
def announce(func: Callable[..., Iterator[float]]) -> Callable[..., Iterator[float]]:
print(f"decorating {func.__name__}")
def wrapper(*args: object) -> Iterator[float]:
print(f"calling {func.__name__}")
return func(*args)
return wrapper
@announce
def high_readings(values: list[float], limit: float) -> Iterator[float]:
for value in values:
print(f" check {value}")
if value > limit:
yield value
print("start")
stream = high_readings([21.4, 23.9, 19.8, 24.6, 25.1], 22.0)
print("created", high_readings.__name__)
print(next(stream))
print(any(value > 24 for value in stream))
print(list(stream))
print(next(stream, "empty"))
checks = [lambda value: value > limit for limit in (22.0, 24.0)]
print([check(23.0) for check in checks])
# TODO: write your prediction for each line before you run it
Hint 1

A decorator runs once, when Python executes the def. The wrapper runs at every call. Calling a generator function runs none of its body: it only creates the generator.

Hint 2

any() stops at the first true value. A generator remembers where it stopped, so list(stream) continues from there. next(it, default) returns the default instead of raising StopIteration. When does a lambda read the variable limit: when it is created, or when it is called?

Solution
from collections.abc import Callable, Iterator
def announce(func: Callable[..., Iterator[float]]) -> Callable[..., Iterator[float]]:
print(f"decorating {func.__name__}")
def wrapper(*args: object) -> Iterator[float]:
print(f"calling {func.__name__}")
return func(*args)
return wrapper
@announce
def high_readings(values: list[float], limit: float) -> Iterator[float]:
for value in values:
print(f" check {value}")
if value > limit:
yield value
print("start")
stream = high_readings([21.4, 23.9, 19.8, 24.6, 25.1], 22.0)
print("created", high_readings.__name__)
print(next(stream))
print(any(value > 24 for value in stream))
print(list(stream))
print(next(stream, "empty"))
checks = [lambda value: value > limit for limit in (22.0, 24.0)]
print([check(23.0) for check in checks])
assert high_readings.__name__ == "wrapper"
assert [check(23.0) for check in checks] == [False, False]
Output
decorating high_readings
start
calling high_readings
created wrapper
check 21.4
check 23.9
23.9
check 19.8
check 24.6
True
check 25.1
[25.1]
empty
[False, False]

How it works:

  1. @announce runs announce(high_readings) at definition time, so decorating ... comes before start (module 11).
  2. Calling the decorated function runs the wrapper, which prints calling .... The wrapper then calls the generator function, which only creates a generator object. No check line appears yet (module 10).
  3. The wrapper has no @functools.wraps(func), so the name is now wrapper. Add wraps and the line reads created high_readings.
  4. next() runs the body up to the first yield: 21.4 fails the test, 23.9 passes and is returned.
  5. any() pulls items until one is true. 24.6 is the first value above 24, so any() stops there, and 25.1 is not checked yet (module 13).
  6. list() drains the rest: one more check and [25.1]. The generator is now exhausted, so next(stream, "empty") returns the default.
  7. Both lambdas read limit when they are called, not when they are created. By then the loop has ended with limit = 24.0, so both test 23.0 > 24.0. This is the late-binding gotcha (module 13). Ruff reports it as B023; in your own code, fix it instead of keeping it. Bind the value at creation time with a default: lambda value, limit=limit: value > limit gives [True, False].

P2-02 · Fix the bugs: a typed readings summary

Section titled “P2-02 · Fix the bugs: a typed readings summary”
Warm-up

Fix the bugs: summarize() should return the count, the mean and the maximum of the valid readings in data/readings.txt. The data dictionary says there are 40 valid values with a mean of 21.06. The script calls it twice, once for the whole file and once for the first 5 lines, and gets wrong results:

from collections.abc import Iterable, Iterator
from itertools import islice
def parse(lines: Iterable[str]) -> Iterator[float]:
for line in lines:
try:
yield float(line)
except ValueError:
pass
def summarize(
values: Iterable[float], seen: list[float] = []
) -> tuple[int, float, float]:
seen.extend(values)
return len(seen), sum(values) / len(seen), max(seen)
with open("data/readings.txt", encoding="utf-8") as file:
print(summarize(parse(file)))
with open("data/readings.txt", encoding="utf-8") as file:
print(summarize(parse(islice(file, 5))))
Output
(40, 0.0, 22.9)
(45, 0.0, 22.9)

Fix both bugs. Also make summarize() return None when there is no valid reading, say so in the return hint, and handle None in a show() function that prints the summary. Call it for the whole file, the first 5 lines and the list ["error", "", "n/a"].

Expected output
40 readings, mean 21.06, max 22.9
5 readings, mean 21.62, max 22.1
no valid readings
Starter
from collections.abc import Iterable, Iterator
from itertools import islice
def parse(lines: Iterable[str]) -> Iterator[float]:
for line in lines:
try:
yield float(line)
except ValueError:
pass
def summarize(
values: Iterable[float], seen: list[float] = []
) -> tuple[int, float, float]:
seen.extend(values)
return len(seen), sum(values) / len(seen), max(seen)
# TODO: fix the bugs, return None without valid readings, and write show()
Hint 1

The default list is created once, when Python defines the function. Every call that does not pass seen shares it. Why does the second call report 45 readings?

Hint 2

parse() returns a generator. What is left in a generator after extend() has read it, and what does sum() of that give?

Solution
from collections.abc import Iterable, Iterator
from itertools import islice
def parse(lines: Iterable[str]) -> Iterator[float]:
for line in lines:
try:
yield float(line)
except ValueError:
pass
def summarize(values: Iterable[float]) -> tuple[int, float, float] | None:
"""Return (count, mean, max) of the values, or None when there are none."""
data = list(values)
if not data:
return None
return len(data), sum(data) / len(data), max(data)
def show(summary: tuple[int, float, float] | None) -> None:
if summary is None:
print("no valid readings")
return
count, mean, high = summary
print(f"{count} readings, mean {mean:.2f}, max {high}")
with open("data/readings.txt", encoding="utf-8") as file:
whole = summarize(parse(file))
with open("data/readings.txt", encoding="utf-8") as file:
head = summarize(parse(islice(file, 5)))
none_valid = summarize(parse(["error", "", "n/a"]))
show(whole)
show(head)
show(none_valid)
assert whole is not None and whole[0] == 40
assert head is not None and head[0] == 5
assert none_valid is None
Output
40 readings, mean 21.06, max 22.9
5 readings, mean 21.62, max 22.1
no valid readings

How it works:

  1. Mutable default (module 13): seen=[] is evaluated once. The second call adds 5 values to the 40 of the first call, so it reports 45. A local data = list(values) starts empty at every call.
  2. One-pass iterator (module 10): parse() returns a generator. extend() drains it, so sum(values) adds nothing and the mean is 0.0. One list() call gives a container that you can read many times.
  3. Honest hints (module 12): the return hint tuple[int, float, float] | None tells the caller that None is possible. Inside show(), the is None check narrows the type, so the unpacking after it is safe. A type checker would flag the unpacking without that check.
  4. parse() uses EAFP: it tries float() and catches only ValueError, which covers error, the empty line and n/a.

P2-03 · Fix the bugs: three checks that lie

Section titled “P2-03 · Fix the bugs: three checks that lie”
Warm-up

Fix the bugs: a catalog audit removes the Books category from data/products.csv, checks the Electronics price total, and compares the units sold in data/sales.csv with the 29,533 units of the data dictionary. The 5 Electronics list prices add up to 2,976.98. All three printed checks are wrong:

import csv
EXPECTED_UNITS = 29533 # from the data dictionary
EXPECTED_ELECTRONICS = 2976.98 # sum of the 5 Electronics list prices
with open("data/products.csv", encoding="utf-8", newline="") as file:
products = list(csv.DictReader(file))
for product in products: # the shop stops selling books
if product["category"] == "Books":
products.remove(product)
books = [p["product_id"] for p in products if p["category"] == "Books"]
print(f"products left: {len(products)}, books left: {books}")
total = 0.0
for product in products:
if product["category"] == "Electronics":
total += float(product["unit_price"])
print(f"Electronics total {total} == {EXPECTED_ELECTRONICS}: {total == EXPECTED_ELECTRONICS}")
with open("data/sales.csv", encoding="utf-8", newline="") as file:
units = sum(int(row["quantity"]) for row in csv.DictReader(file))
print(f"units {units} match: {units is EXPECTED_UNITS}")
Output
products left: 27, books left: ['P022', 'P024']
Electronics total 2976.9799999999996 == 2976.98: False
units 29533 match: False

Fix the three bugs. Keep the loop that adds the Electronics prices one by one.

Expected output
products left: 25, books left: []
Electronics total 2976.98 matches 2976.98: True
units 29533 match: True
Starter
import csv
import math
EXPECTED_UNITS = 29533 # from the data dictionary
EXPECTED_ELECTRONICS = 2976.98 # sum of the 5 Electronics list prices
with open("data/products.csv", encoding="utf-8", newline="") as file:
products = list(csv.DictReader(file))
# TODO: fix the three checks of the script above
Hint 1

The Books products are P021 to P025, next to each other in the file. Which index does the loop visit after it removes P021?

Hint 2

Can 2,976.98 be stored exactly as a binary float? And what does is compare: values or objects?

Solution
import csv
import math
EXPECTED_UNITS = 29533 # from the data dictionary
EXPECTED_ELECTRONICS = 2976.98 # sum of the 5 Electronics list prices
with open("data/products.csv", encoding="utf-8", newline="") as file:
products = list(csv.DictReader(file))
products = [p for p in products if p["category"] != "Books"]
books = [p["product_id"] for p in products if p["category"] == "Books"]
print(f"products left: {len(products)}, books left: {books}")
total = 0.0
for product in products:
if product["category"] == "Electronics":
total += float(product["unit_price"])
ok = math.isclose(total, EXPECTED_ELECTRONICS, abs_tol=0.005)
print(f"Electronics total {total:.2f} matches {EXPECTED_ELECTRONICS}: {ok}")
with open("data/sales.csv", encoding="utf-8", newline="") as file:
units = sum(int(row["quantity"]) for row in csv.DictReader(file))
print(f"units {units} match: {units == EXPECTED_UNITS}")
assert len(products) == 25 and not books
assert ok and units == EXPECTED_UNITS
assert total != EXPECTED_ELECTRONICS # the float sum is not exact
Output
products left: 25, books left: []
Electronics total 2976.98 matches 2976.98: True
units 29533 match: True

How it works:

  1. Changing a list while you loop over it (module 13): remove() shifts the next items one place left, but the loop index moves on. After P021 is removed, P022 sits at the visited index and is skipped, and so is P024. A comprehension builds a new list and never skips.
  2. Float precision: decimal prices such as 79.99 have no exact binary form. Adding them one by one leaves a tiny error, 2976.9799999999996. Compare floats with math.isclose() and a tolerance of half a cent. Since Python 3.12, the built-in sum() of floats compensates the rounding errors and happens to give exactly 2976.98 here; math.fsum() always does. Do not rely on either for an == test.
  3. is versus ==: is asks whether two names point to the same object. The sum creates a new int object, so is is False although the values are equal. Use == for values and keep is for None.
  4. The units come from a generator expression inside sum(), which reads the 20,228 lines without building a list (module 10). The check assert total != EXPECTED_ELECTRONICS documents that the float error is real.

P2-04 · Count what each generator stage yields

Section titled “P2-04 · Count what each generator stage yields”
Core

A streaming pipeline reads data/sensors.csv, keeps the rows with a vibration value, and passes on the readings at or above the warning level of 4.5 mm/s. You want to know how many items each stage yields, without changing the stages.

Write a decorator counted for generator functions. It counts every item that the generator yields in a module-level Counter, under the function’s name. Keep the name and the docstring with functools.wraps, and type it so that the decorated function keeps its signature. Decorate three stages, consume the pipeline in chunks of 100 with itertools.batched, count the chunks too, and print the counts and the alerts per sensor. Print the counts once before the sink runs, to show that the pipeline is lazy.

Expected output
before the sink: {}
read_rows 8,064
with_vibration 8,034
above 441
chunk 5
alerts by sensor: {'S1': 7, 'S2': 10, 'S3': 13, 'S4': 411}
above | read_rows

The last line prints above.__name__ and read_rows.__wrapped__.__name__.

Starter
import csv
import functools
from collections import Counter
from collections.abc import Callable, Iterable, Iterator
from itertools import batched
type Reading = tuple[str, str, float] # timestamp, sensor_id, vibration
counts: Counter[str] = Counter()
def counted(func): # TODO: type it with [**P, T] and Callable
# TODO: a generator wrapper that counts and re-yields each item
...
def read_rows(path: str) -> Iterator[dict[str, str]]:
... # TODO: yield the rows of csv.DictReader
def with_vibration(rows: Iterable[dict[str, str]]) -> Iterator[Reading]:
... # TODO: yield (timestamp, sensor_id, float(vibration)); skip blanks
def above(readings: Iterable[Reading], limit: float) -> Iterator[Reading]:
... # TODO: yield the readings with vibration >= limit
# TODO: build the pipeline, print the counts, consume it with batched(..., 100)
Hint 1

The wrapper itself is a generator: for item in func(*args, **kwargs): counts[func.__name__] += 1 and then yield item. Nothing runs until somebody pulls the first item.

Hint 2

A parameter specification keeps the parameters of the decorated function. In the PEP 695 form, declare it with the type parameters [**P, T], take a Callable whose return type is an iterator of T, and type the wrapper’s parameters with P.args and P.kwargs.

Solution
import csv
import functools
from collections import Counter
from collections.abc import Callable, Iterable, Iterator
from itertools import batched
type Reading = tuple[str, str, float] # timestamp, sensor_id, vibration
counts: Counter[str] = Counter()
def counted[**P, T](func: Callable[P, Iterator[T]]) -> Callable[P, Iterator[T]]:
"""Count the items that a generator function yields, under its name."""
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> Iterator[T]:
for item in func(*args, **kwargs):
counts[func.__name__] += 1
yield item
return wrapper
@counted
def read_rows(path: str) -> Iterator[dict[str, str]]:
with open(path, encoding="utf-8", newline="") as file:
yield from csv.DictReader(file)
@counted
def with_vibration(rows: Iterable[dict[str, str]]) -> Iterator[Reading]:
for row in rows:
try:
yield row["timestamp"], row["sensor_id"], float(row["vibration_mm_s"])
except ValueError:
continue
@counted
def above(readings: Iterable[Reading], limit: float) -> Iterator[Reading]:
for reading in readings:
if reading[2] >= limit:
yield reading
pipeline = above(with_vibration(read_rows("data/sensors.csv")), limit=4.5)
print("before the sink:", dict(counts))
by_sensor: Counter[str] = Counter()
for chunk in batched(pipeline, 100):
counts["chunk"] += 1
by_sensor.update(sensor for _, sensor, _ in chunk)
for stage in ("read_rows", "with_vibration", "above", "chunk"):
print(f"{stage:<15}{counts[stage]:>6,}")
print("alerts by sensor:", dict(sorted(by_sensor.items())))
print(above.__name__, "|", read_rows.__wrapped__.__name__)
assert counts["read_rows"] == 8064
assert counts["read_rows"] - counts["with_vibration"] == 30
assert by_sensor.total() == counts["above"]
Output
before the sink: {}
read_rows 8,064
with_vibration 8,034
above 441
chunk 5
alerts by sensor: {'S1': 7, 'S2': 10, 'S3': 13, 'S4': 411}
above | read_rows

How it works:

  1. The three calls in the pipeline = line only create generators. The counter is still empty, which proves that no row was read (module 10).
  2. batched(pipeline, 100) pulls items through all three stages. Each pull passes through each wrapper, so every stage counts its own output. 441 alerts make 4 full chunks and one chunk of 41.
  3. 30 rows have a blank vibration cell, as the data dictionary says. float("") raises ValueError, and the stage skips them.
  4. functools.wraps copies __name__ and __doc__ and adds __wrapped__, the original function (module 11). The **P parameter specification keeps the real parameters for a type checker: above(rows, limit="x") would be an error (module 12).
  5. Most alerts come from S4, the sensor with bearing wear from May 12.
Section titled “P2-05 · A product table from an API with a broken next link”
Core

The shop API returns 10 products per page and a next link to the following page (see data/api/products_page_1.json). A server bug sometimes makes the last page link back to the first one, so a naive client loops forever. Write a client that collects every product offline, with the make_client() helper of the starter.

  1. Write a generator iter_products(client) that follows the next links and checks every status. Remember each URL that it has fetched. When a next link points to one of them, raise RuntimeError with the link in the message.
  2. Describe a product record with TypedDict classes.
  3. Print the count of products and unique ids, the out-of-stock ids and the 3 best-rated products. Break rating ties by the number of reviews.
  4. Write a recursive flatten() that turns nested dicts into dotted keys (price.amount). Print the dotted columns, write all rows to output/products_flat.csv and read the file back.
  5. Run iter_products() against make_client(loop=True). Count the products that arrive before the error, and print the error.
Expected output
30 products, 30 unique ids
out of stock: ['P006', 'P019']
P018 Adjustable Dumbbells 4.3 (53)
P008 Chef's Knife Set 4.2 (117)
P021 Harbor Lane Mysteries 4.2 (115)
dotted columns: price.amount, price.currency, rating.average, rating.count
wrote 30 rows, first price 79.99
looping API: stopped after 30 products
next link loops back to https://api.example.com/v1/products?page=1&per_page=10
Starter
import json
from collections.abc import Callable
from pathlib import Path
import httpx
def make_handler(loop: bool = False) -> Callable[[httpx.Request], httpx.Response]:
"""Serve the saved pages. With loop=True, page 3 links back to page 1."""
def handler(request: httpx.Request) -> httpx.Response:
page = request.url.params.get("page", "1")
path = Path(f"data/api/products_page_{page}.json")
if request.url.path != "/v1/products" or not path.exists():
return httpx.Response(404, json={"error": "not_found"})
body = json.loads(path.read_text(encoding="utf-8"))
if loop and page == "3":
body["next"] = "https://api.example.com/v1/products?page=1&per_page=10"
return httpx.Response(200, json=body)
return handler
def make_client(loop: bool = False) -> httpx.Client:
return httpx.Client(
base_url="https://api.example.com/v1",
transport=httpx.MockTransport(make_handler(loop)),
)
# TODO: TypedDicts Price, Rating and Product
# TODO: iter_products(client) -> Iterator[Product], with loop detection
# TODO: flatten(record, prefix="") -> dict[str, object]
# TODO: the report, the CSV file and the run against make_client(loop=True)
Hint 1

yield from body["data"] yields the products of one page. The next value is a full URL or None. client.get() accepts a full URL as well as a path relative to base_url, and str(response.url) gives the full URL that was fetched, in the same form as the next links.

Hint 2

flatten() calls itself when a value is a Mapping, with the prefix f"{prefix}{key}.". A tuple key such as (average, count) breaks ties in heapq.nlargest. Consume the looping generator in a for loop inside try, so that you keep the products that arrived before the error.

Solution
import csv
import heapq
import json
from collections.abc import Callable, Iterator, Mapping
from pathlib import Path
from typing import TypedDict
import httpx
class Price(TypedDict):
amount: float
currency: str
class Rating(TypedDict):
average: float
count: int
class Product(TypedDict):
id: str
name: str
category: str
price: Price
in_stock: bool
stock: int
rating: Rating
launch_date: str
url: str
def make_handler(loop: bool = False) -> Callable[[httpx.Request], httpx.Response]:
"""Serve the saved pages. With loop=True, page 3 links back to page 1."""
def handler(request: httpx.Request) -> httpx.Response:
page = request.url.params.get("page", "1")
path = Path(f"data/api/products_page_{page}.json")
if request.url.path != "/v1/products" or not path.exists():
return httpx.Response(404, json={"error": "not_found"})
body = json.loads(path.read_text(encoding="utf-8"))
if loop and page == "3":
body["next"] = "https://api.example.com/v1/products?page=1&per_page=10"
return httpx.Response(200, json=body)
return handler
def iter_products(client: httpx.Client) -> Iterator[Product]:
"""Yield every product, following the next links; stop on a loop."""
url: str | None = "/products?page=1&per_page=10"
seen: set[str] = set()
while url is not None:
response = client.get(url)
response.raise_for_status()
seen.add(str(response.url))
body = response.json()
yield from body["data"]
url = body["next"]
if url in seen:
raise RuntimeError(f"next link loops back to {url}")
def make_client(loop: bool = False) -> httpx.Client:
return httpx.Client(
base_url="https://api.example.com/v1",
transport=httpx.MockTransport(make_handler(loop)),
)
def flatten(record: Mapping[str, object], prefix: str = "") -> dict[str, object]:
"""Turn nested dicts into one level with dotted keys."""
flat: dict[str, object] = {}
for key, value in record.items():
if isinstance(value, Mapping):
flat.update(flatten(value, prefix=f"{prefix}{key}."))
else:
flat[f"{prefix}{key}"] = value
return flat
with make_client() as client:
products = list(iter_products(client))
ids = {product["id"] for product in products}
print(f"{len(products)} products, {len(ids)} unique ids")
print("out of stock:", [p["id"] for p in products if not p["in_stock"]])
best = heapq.nlargest(
3, products, key=lambda p: (p["rating"]["average"], p["rating"]["count"])
)
for p in best:
rating = p["rating"]
print(f" {p['id']} {p['name']:<24} {rating['average']} ({rating['count']})")
rows = [flatten(product) for product in products]
print("dotted columns:", ", ".join(name for name in rows[0] if "." in name))
Path("output").mkdir(exist_ok=True)
with open("output/products_flat.csv", "w", encoding="utf-8", newline="") as file:
writer = csv.DictWriter(file, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
with open("output/products_flat.csv", encoding="utf-8", newline="") as file:
back = list(csv.DictReader(file))
print(f"wrote {len(back)} rows, first price {back[0]['price.amount']}")
got: list[Product] = []
with make_client(loop=True) as client:
try:
for product in iter_products(client):
got.append(product)
except RuntimeError as error:
print(f"looping API: stopped after {len(got)} products")
print(f" {error}")
assert len(got) == 30
assert len(ids) == 30
assert len(rows[0]) == 11
assert back[0]["price.amount"] == "79.99"
Output
30 products, 30 unique ids
out of stock: ['P006', 'P019']
P018 Adjustable Dumbbells 4.3 (53)
P008 Chef's Knife Set 4.2 (117)
P021 Harbor Lane Mysteries 4.2 (115)
dotted columns: price.amount, price.currency, rating.average, rating.count
wrote 30 rows, first price 79.99
looping API: stopped after 30 products
next link loops back to https://api.example.com/v1/products?page=1&per_page=10

How it works:

  1. iter_products is a generator, so it fetches a page only when the caller needs its items (module 10). raise_for_status() turns a 4xx or 5xx answer into an exception before you read the body (module 16).
  2. The set seen holds every fetched URL. A membership test costs O(1)O(1) (module 17), and a repeated URL proves that the links form a cycle. Unlike a fixed page limit, this check never stops a long but correct listing, and it fails at the first repeat.
  3. The check runs after yield from, so the 30 products of the looping API reach the caller before the error. The caller decides what to keep.
  4. The TypedDict classes tell the reader and the type checker which keys exist, for example p["rating"]["count"]. At runtime the records stay plain dicts (module 12).
  5. flatten() is recursive: each nested level calls flatten() again with a longer prefix (module 17). The records are only two levels deep, so recursion is safe here. For deep data, use a loop with a list as a stack.
  6. The API rounds the mean rating to one decimal, so P008 and P021 tie at 4.2. The review count breaks the tie. Exercise P2-09 computes the exact means from data/reviews.csv.

P2-06 · Write and test the catalog scraper

Section titled “P2-06 · Write and test the catalog scraper”
Core

Write the scraper and its tests: the shop’s catalog page data/api/catalog.html has a price table (table#products), 12 product cards (article.product-card) with a link to each product page, and a rel="next" link to the next catalog page. Build a small project with the layout below. Run every command from the project folder, where data/ is.

pyproject.toml # pytest and coverage settings (given)
src/catalog.py # the scraper
tests/conftest.py # shared fixtures
tests/test_catalog.py # the tests
pyproject.toml
[tool.pytest]
testpaths = ["tests"]
pythonpath = ["src"]
strict = true
[tool.coverage.report]
show_missing = true
exclude_also = ['if __name__ == "__main__":']
  1. In src/catalog.py, write parse_catalog(), product_links() and next_page() with BeautifulSoup and CSS selectors. Make links absolute with urljoin() and the base URL https://shop.example.com. mypy --strict must accept the module.
  2. In tests/conftest.py, write a session-scoped fixture html that reads the page once, and a fixture rows that parses it.
  3. In tests/test_catalog.py, check: parse_price() on 4 good inputs, as one parametrized test with readable IDs; ValueError with the message not a price for bad text; 12 unique products from P001 to P012, the decoded entity in Chef&#x27;s Knife Set, the price of P003 and that only P006 is out of stock; the absolute link of P008; the next-page link, and None on a page without one; a CSV round trip in a temporary folder; and that report() follows the PRICE_ALERT environment variable, from its printed output.

Acceptance criteria:

  • python src/catalog.py prints 2 of 12 products above 500: ['P003', 'P004'].
  • pytest -q passes with 0 failures and at least 12 tests, and coverage report shows 100% for src/catalog.py.
  • The tests import catalog without any sys.path change; the pythonpath setting does that.
  • Your suite never changes the real environment and never writes into the project folder.
  • Break parse_price() on purpose (delete .replace(",", "")). At least one test fails, and its report names the input.
src/catalog.py (starter)
"""Scrape the price table and the links of the shop's catalog page."""
import csv
import os
from pathlib import Path
from typing import TypedDict
from urllib.parse import urljoin
from bs4 import BeautifulSoup
BASE_URL = "https://shop.example.com"
class Row(TypedDict):
id: str
name: str
price: float
in_stock: bool
def parse_price(text: str) -> float:
"""Turn a price such as '$1,299.00' into 1299.0."""
cleaned = text.strip().removeprefix("$").replace(",", "")
try:
return float(cleaned)
except ValueError:
raise ValueError(f"not a price: {text!r}") from None
def parse_catalog(html: str) -> list[Row]:
"""Return one Row per line of the table#products."""
... # TODO: CSS selectors for the rows and cells; parse_price for the price
def product_links(html: str) -> dict[str, str]:
"""Map each product card's id to the absolute URL of its page."""
... # TODO: article.product-card, its data-product-id and its h2 link
def next_page(html: str) -> str | None:
"""Return the absolute URL of the rel="next" link, or None on the last page."""
... # TODO: urljoin(BASE_URL, href) or None
def write_csv(rows: list[Row], path: Path) -> None:
with open(path, "w", encoding="utf-8", newline="") as file:
writer = csv.DictWriter(file, fieldnames=list(Row.__annotations__))
writer.writeheader()
writer.writerows(rows)
def report(rows: list[Row]) -> None:
"""Print the products that cost more than PRICE_ALERT (default 500)."""
limit = float(os.environ.get("PRICE_ALERT", "500"))
expensive = [row["id"] for row in rows if row["price"] > limit]
print(f"{len(expensive)} of {len(rows)} products above {limit:.0f}: {expensive}")
Hint 1

soup.select("table#products tbody tr") returns the rows; tr["data-id"] reads an attribute. select_one() returns None when nothing matches, so mypy makes you check it before you call get_text(). select() always returns a list, which needs no check.

Hint 2

pytest finds the fixtures of tests/conftest.py in every test file of that folder without an import. A test can request several fixtures by name: rows, html, tmp_path, monkeypatch and capsys.

Solution
src/catalog.py
"""Scrape the price table and the links of the shop's catalog page."""
import csv
import os
from pathlib import Path
from typing import TypedDict
from urllib.parse import urljoin
from bs4 import BeautifulSoup
BASE_URL = "https://shop.example.com"
class Row(TypedDict):
id: str
name: str
price: float
in_stock: bool
def parse_price(text: str) -> float:
"""Turn a price such as '$1,299.00' into 1299.0."""
cleaned = text.strip().removeprefix("$").replace(",", "")
try:
return float(cleaned)
except ValueError:
raise ValueError(f"not a price: {text!r}") from None
def parse_catalog(html: str) -> list[Row]:
"""Return one Row per line of the table#products."""
soup = BeautifulSoup(html, "html.parser")
rows: list[Row] = []
for tr in soup.select("table#products tbody tr"):
cells = [td.get_text(strip=True) for td in tr.select("td")]
rows.append(
{
"id": str(tr["data-id"]),
"name": cells[1],
"price": parse_price(cells[3]),
"in_stock": cells[4] == "In stock",
}
)
return rows
def product_links(html: str) -> dict[str, str]:
"""Map each product card's id to the absolute URL of its page."""
soup = BeautifulSoup(html, "html.parser")
links: dict[str, str] = {}
for card in soup.select("article.product-card[data-product-id]"):
for link in card.select("h2.product-name a[href]"):
links[str(card["data-product-id"])] = urljoin(BASE_URL, str(link["href"]))
return links
def next_page(html: str) -> str | None:
"""Return the absolute URL of the rel="next" link, or None on the last page."""
link = BeautifulSoup(html, "html.parser").select_one('a[rel="next"]')
return None if link is None else urljoin(BASE_URL, str(link["href"]))
def write_csv(rows: list[Row], path: Path) -> None:
with open(path, "w", encoding="utf-8", newline="") as file:
writer = csv.DictWriter(file, fieldnames=list(Row.__annotations__))
writer.writeheader()
writer.writerows(rows)
def report(rows: list[Row]) -> None:
"""Print the products that cost more than PRICE_ALERT (default 500)."""
limit = float(os.environ.get("PRICE_ALERT", "500"))
expensive = [row["id"] for row in rows if row["price"] > limit]
print(f"{len(expensive)} of {len(rows)} products above {limit:.0f}: {expensive}")
if __name__ == "__main__": # smoke check: python src/catalog.py
page = Path("data/api/catalog.html").read_text(encoding="utf-8")
rows = parse_catalog(page)
assert len(rows) == 12
assert next_page(page) is not None
report(rows)
Output
2 of 12 products above 500: ['P003', 'P004']
tests/conftest.py
"""Fixtures shared by every test file in tests/."""
from pathlib import Path
import pytest
from catalog import Row, parse_catalog
@pytest.fixture(scope="session")
def html() -> str:
return Path("data/api/catalog.html").read_text(encoding="utf-8")
@pytest.fixture
def rows(html: str) -> list[Row]:
return parse_catalog(html)
tests/test_catalog.py
"""Tests for src/catalog.py. Run from the project folder: pytest -q"""
import csv
from pathlib import Path
import pytest
from catalog import Row, next_page, parse_price, product_links, report, write_csv
@pytest.mark.parametrize(
("text", "expected"),
[
("$79.99", 79.99),
("$1,299.00", 1299.0),
(" $14.99 ", 14.99),
("249", 249.0),
],
ids=["plain", "thousands", "spaces", "no-symbol"],
)
def test_parse_price(text: str, expected: float) -> None:
assert parse_price(text) == pytest.approx(expected)
@pytest.mark.parametrize("text", ["", "N/A", "$12.50.1"])
def test_parse_price_rejects_bad_text(text: str) -> None:
with pytest.raises(ValueError, match="not a price"):
parse_price(text)
def test_table_has_twelve_unique_products(rows: list[Row]) -> None:
ids = [row["id"] for row in rows]
assert len(set(ids)) == len(ids) == 12
assert ids[0] == "P001" and ids[-1] == "P012"
def test_entities_and_stock(rows: list[Row]) -> None:
by_id = {row["id"]: row for row in rows}
assert by_id["P008"]["name"] == "Chef's Knife Set"
assert by_id["P003"]["price"] == 1299.0
assert [row["id"] for row in rows if not row["in_stock"]] == ["P006"]
def test_links_are_absolute(html: str) -> None:
links = product_links(html)
assert len(links) == 12
assert links["P008"] == "https://shop.example.com/products/p008-chef-s-knife-set"
def test_next_page(html: str) -> None:
assert next_page(html) == "https://shop.example.com/catalog?page=2"
assert next_page("<p>last page</p>") is None
def test_write_csv_round_trip(rows: list[Row], tmp_path: Path) -> None:
path = tmp_path / "prices.csv"
write_csv(rows, path)
with open(path, encoding="utf-8", newline="") as file:
back = list(csv.DictReader(file))
assert len(back) == 12
assert back[2] == {
"id": "P003",
"name": "55-inch 4K Smart TV",
"price": "1299.0",
"in_stock": "True",
}
def test_report_uses_the_env_limit(
rows: list[Row],
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
) -> None:
report(rows)
monkeypatch.setenv("PRICE_ALERT", "200")
report(rows)
assert capsys.readouterr().out.splitlines() == [
"2 of 12 products above 500: ['P003', 'P004']",
"5 of 12 products above 200: ['P002', 'P003', 'P004', 'P006', 'P007']",
]
Terminal
pytest -q --cov=catalog --cov-report=
coverage report
Output
............. [100%]
13 passed in 0.16s
Name Stmts Miss Cover Missing
----------------------------------------------
src/catalog.py 44 0 100%
----------------------------------------------
TOTAL 44 0 100%

How it works:

  1. The CSS selectors describe the structure, not positions in the file: article.product-card[data-product-id] is an <article> with that class and attribute, and h2.product-name a[href] is a link inside its heading (module 16). urljoin() turns /products/p008-chef-s-knife-set into an absolute URL.
  2. next_page() uses select_one() and narrows its None result, so mypy --strict accepts the module (module 12). parse_catalog() reads the cells with select(), which returns a list, and needs no check.
  3. pythonpath = ["src"] puts src/ on the import path for the tests, and testpaths makes a plain pytest run collect tests/ only (module 14). The src/ layout keeps tests and code apart.
  4. conftest.py shares fixtures with every test file in its folder. html has scope="session", so the file is read once per run. rows has the default function scope, so each test gets a fresh list and cannot spoil another test’s data.
  5. tmp_path is a new empty folder for each test, so the round trip never touches output/. monkeypatch.setenv() sets PRICE_ALERT for one test only, and capsys captures what report() prints.
  6. Coverage counts 44 statements in src/catalog.py, all run by the tests. exclude_also leaves out the smoke check under the main guard, which only the python src/catalog.py run uses.
  7. With .replace(",", "") removed, test_parse_price[thousands] fails. The rows fixture also raises, because the table holds $1,299.00, so pytest reports the tests that use it as errors. The test ID [thousands] names the broken case.

P2-07 · Interpret and refactor: a slow churn report

Section titled “P2-07 · Interpret and refactor: a slow churn report”
Core

Interpret the profile, then refactor: slow_report() counts the 2024 sales lines of churned customers per month. It is correct but slow. Do the work in four steps:

  1. Run it under cProfile with its output captured by redirect_stdout. Print the call counts of churned_ids, lines_in_month and the built-in sorted, and the name of the function with the most own time (tottime).
  2. Explain in two sentences where the time goes.
  3. Write fast_report() with the same output. Use a set and sort the dates once, then count each month with bisect.
  4. Prove that the output did not change. Measure both versions with timeit.repeat() and check that the new one is at least 10 times faster. Then print the new report.
Expected output
churned_ids: 1 calls
lines_in_month: 12 calls
<built-in method builtins.sorted>: 12 calls
most own time: slow_report
same output: True
fast is at least 10 times faster: True
2568 lines from churned customers
2024-01 77
2024-02 69
2024-03 89
2024-04 93
2024-05 94
2024-06 135
2024-07 119
2024-08 134
2024-09 156
2024-10 147
2024-11 262
2024-12 330
Starter
import csv
def load(path: str) -> list[dict[str, str]]:
with open(path, encoding="utf-8", newline="") as file:
return list(csv.DictReader(file))
def churned_ids(customers: list[dict[str, str]]) -> list[str]:
return [row["customer_id"] for row in customers if row["churned"] == "1"]
def lines_in_month(rows: list[dict[str, str]], month: str) -> int:
dates = sorted(row["order_date"] for row in rows)
return len([d for d in dates if d.startswith(month)])
def slow_report(sales: list[dict[str, str]], customers: list[dict[str, str]]) -> None:
ids = churned_ids(customers)
lost = [row for row in sales if row["customer_id"] in ids]
print(f"{len(lost)} lines from churned customers")
for m in range(1, 13):
month = f"2024-{m:02d}"
print(month, lines_in_month(lost, month))
sales = load("data/sales.csv")
customers = load("data/customers.csv")
# TODO: profile slow_report with its output captured
# TODO: print the call counts and the function with the most own time
# TODO: write fast_report, then compare the outputs and the times
Hint 1

pstats.Stats(profiler).get_stats_profile() returns an object whose func_profiles dict maps each function name to its numbers. Each entry has ncalls (a string) and tottime. timeit.repeat(func, number=1, repeat=3) returns 3 timings; keep the smallest.

Hint 2

The comprehension inside slow_report tests customer_id in ids, and ids is a list of 963 ids. In a sorted list of YYYY-MM-DD strings, the lines of 2024-03 sit between bisect_left(dates, "2024-03") and bisect_left(dates, "2024-03-99").

Solution
import cProfile
import csv
import io
import pstats
import timeit
from bisect import bisect_left
from contextlib import redirect_stdout
def load(path: str) -> list[dict[str, str]]:
with open(path, encoding="utf-8", newline="") as file:
return list(csv.DictReader(file))
def churned_ids(customers: list[dict[str, str]]) -> list[str]:
return [row["customer_id"] for row in customers if row["churned"] == "1"]
def lines_in_month(rows: list[dict[str, str]], month: str) -> int:
dates = sorted(row["order_date"] for row in rows)
return len([d for d in dates if d.startswith(month)])
def slow_report(sales: list[dict[str, str]], customers: list[dict[str, str]]) -> None:
ids = churned_ids(customers)
lost = [row for row in sales if row["customer_id"] in ids]
print(f"{len(lost)} lines from churned customers")
for m in range(1, 13):
month = f"2024-{m:02d}"
print(month, lines_in_month(lost, month))
def fast_report(sales: list[dict[str, str]], customers: list[dict[str, str]]) -> None:
ids = set(churned_ids(customers))
dates = sorted(row["order_date"] for row in sales if row["customer_id"] in ids)
print(f"{len(dates)} lines from churned customers")
for m in range(1, 13):
month = f"2024-{m:02d}"
print(month, bisect_left(dates, f"{month}-99") - bisect_left(dates, month))
sales = load("data/sales.csv")
customers = load("data/customers.csv")
# 1. Profile the old version; keep its output for the characterization check
profiler = cProfile.Profile()
with redirect_stdout(io.StringIO()) as old_output:
profiler.runcall(slow_report, sales, customers)
functions = pstats.Stats(profiler).get_stats_profile().func_profiles
for name in ("churned_ids", "lines_in_month", "<built-in method builtins.sorted>"):
print(f"{name}: {functions[name].ncalls} calls")
print("most own time:", max(functions, key=lambda name: functions[name].tottime))
# 3-4. Same output, and much faster
with redirect_stdout(io.StringIO()) as new_output:
fast_report(sales, customers)
print("same output:", new_output.getvalue() == old_output.getvalue())
with redirect_stdout(io.StringIO()):
slow = min(timeit.repeat(lambda: slow_report(sales, customers), number=1, repeat=3))
fast = min(timeit.repeat(lambda: fast_report(sales, customers), number=1, repeat=3))
print("fast is at least 10 times faster:", fast * 10 < slow)
print(new_output.getvalue(), end="")
assert new_output.getvalue() == old_output.getvalue()
assert functions["lines_in_month"].ncalls == "12"
Output
churned_ids: 1 calls
lines_in_month: 12 calls
<built-in method builtins.sorted>: 12 calls
most own time: slow_report
same output: True
fast is at least 10 times faster: True
2568 lines from churned customers
2024-01 77
2024-02 69
2024-03 89
2024-04 93
2024-05 94
2024-06 135
2024-07 119
2024-08 134
2024-09 156
2024-10 147
2024-11 262
2024-12 330

Interpretation: the function with the most own time is slow_report itself, not a function it calls. Its own line customer_id in ids scans a list of 963 ids for each of the 20,228 lines, millions of string comparisons in total (O(n⋅m)O(n \cdot m)). The second waste is sorted with 12 calls on the same 2,568 dates, where one sort is enough.

How it works:

  1. cProfile counts every call exactly. The times vary from run to run, so the solution prints only the call counts and the name with the largest tottime (module 15). Own time (tottime) excludes the time spent in callees. Since Python 3.12, a list comprehension runs inside the frame of its function (PEP 709), so its time counts as the own time of slow_report. On Python 3.11, the top entry would be <listcomp>.
  2. redirect_stdout is a context manager that sends print() to a StringIO buffer (module 11). The old output becomes the reference for a characterization check: the refactor is correct only if the new output is identical (module 13).
  3. A set makes each membership test O(1)O(1). One sort costs O(nlog⁡n)O(n \log n), and each month then costs two binary searches, O(log⁡n)O(\log n) (module 17).
  4. "2024-03-99" sorts after every real date of March and before "2024-04-01", so the two bisects bound the whole month.
  5. timeit.repeat() runs each version 3 times; the minimum is the run with the least noise from other programs (module 15). The check compares the two minimums instead of printing times, so the output stays the same on every machine. It proves a speedup of at least 10 times; the real factor depends on the machine.

P2-08 · Fix the bugs: a thread-pool page loader

Section titled “P2-08 · Fix the bugs: a thread-pool page loader”
Core

Fix the bugs: this script downloads pages 1 to 4 of the product API at the same time with a thread pool. The fake server answers page 3 first and page 4 last, and page 4 does not exist. The script labels the pages wrongly and then crashes:

import json
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
import httpx
DELAYS = {1: 0.3, 2: 0.2, 3: 0.1, 4: 0.4} # seconds until the server answers
def handler(request: httpx.Request) -> httpx.Response:
page = int(request.url.params["page"])
time.sleep(DELAYS[page])
path = Path(f"data/api/products_page_{page}.json")
if not path.exists():
return httpx.Response(404, json={"error": "not_found"})
return httpx.Response(200, json=json.loads(path.read_text(encoding="utf-8")))
def fetch_page(client: httpx.Client, page: int) -> list[str]:
body = client.get("/products", params={"page": page}).json()
return [product["id"] for product in body["data"]]
pages = [1, 2, 3, 4]
transport = httpx.MockTransport(handler)
with httpx.Client(base_url="https://api.example.com/v1", transport=transport) as client:
with ThreadPoolExecutor(max_workers=4) as pool:
futures = [pool.submit(fetch_page, client, page) for page in pages]
for page, future in zip(pages, as_completed(futures), strict=True):
ids = future.result()
print(f"page {page}: {ids[0]}..{ids[-1]}")
Output
page 1: P021..P030
page 2: P011..P020
page 3: P001..P010
KeyError: 'data'

Fix it so that each page keeps its own result, a missing page is reported with its status code instead of a crash, and the other pages still count. Keep as_completed, so that you can print the finish order.

Expected output
finish order: [3, 2, 1, 4]
page 1: 10 products, P001..P010
page 2: 10 products, P011..P020
page 3: 10 products, P021..P030
page 4: HTTP 404
30 products from 3 pages
Starter
# Keep handler() and DELAYS from the script above.
def fetch_page(client: httpx.Client, page: int) -> list[str]:
response = client.get("/products", params={"page": page})
# TODO: check the status before you read the body
return [product["id"] for product in response.json()["data"]]
pages = [1, 2, 3, 4]
results: dict[int, list[str]] = {}
errors: dict[int, int] = {}
# TODO: map each future to its page, collect results and errors per future
Hint 1

as_completed() yields the futures in finish order, not in the order of pages. zip() pairs them by position anyway. A dict {future: page} remembers which page each future belongs to.

Hint 2

future.result() re-raises the exception of the worker thread. Call raise_for_status() in the worker, and wrap future.result() in try/except httpx.HTTPStatusError, so that one failure does not stop the loop.

Solution
import json
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
import httpx
DELAYS = {1: 0.3, 2: 0.2, 3: 0.1, 4: 0.4} # seconds until the server answers
def handler(request: httpx.Request) -> httpx.Response:
page = int(request.url.params["page"])
time.sleep(DELAYS[page])
path = Path(f"data/api/products_page_{page}.json")
if not path.exists():
return httpx.Response(404, json={"error": "not_found"})
return httpx.Response(200, json=json.loads(path.read_text(encoding="utf-8")))
def fetch_page(client: httpx.Client, page: int) -> list[str]:
response = client.get("/products", params={"page": page})
response.raise_for_status()
return [product["id"] for product in response.json()["data"]]
pages = [1, 2, 3, 4]
results: dict[int, list[str]] = {}
errors: dict[int, int] = {}
finished: list[int] = []
transport = httpx.MockTransport(handler)
with httpx.Client(base_url="https://api.example.com/v1", transport=transport) as client:
with ThreadPoolExecutor(max_workers=4) as pool:
futures = {pool.submit(fetch_page, client, page): page for page in pages}
for future in as_completed(futures):
page = futures[future]
finished.append(page)
try:
results[page] = future.result()
except httpx.HTTPStatusError as error:
errors[page] = error.response.status_code
print("finish order:", finished)
for page in pages:
if page in results:
ids = results[page]
print(f"page {page}: {len(ids)} products, {ids[0]}..{ids[-1]}")
else:
print(f"page {page}: HTTP {errors[page]}")
total = sum(len(ids) for ids in results.values())
print(f"{total} products from {len(results)} pages")
assert total == 30
assert errors == {4: 404}
Output
finish order: [3, 2, 1, 4]
page 1: 10 products, P001..P010
page 2: 10 products, P011..P020
page 3: 10 products, P021..P030
page 4: HTTP 404
30 products from 3 pages

How it works:

  1. Wrong labels (module 15): as_completed() yields page 3 first, but zip() pairs it with the first item of pages, which is 1. The dict {future: page} keeps the link between a future and its input. If you do not need the finish order, pool.map(...) returns the results in input order.
  2. Crash on the missing page (module 16): the 404 body has no data key, so the old code fails with a KeyError that hides the real cause. raise_for_status() raises httpx.HTTPStatusError with the status code, which the loop records.
  3. One error stops everything: the exception of a worker is stored in its future. future.result() re-raises it in the main thread. Catching it per future lets the other pages finish.
  4. The 4 requests overlap, so the run takes about 0.4 s (the slowest page), not 1.0 s (the sum). The work is waiting for I/O, so threads help in spite of the GIL.
  5. The type hints dict[int, list[str]] and dict[int, int] tell the reader at a glance what each dict maps (module 12).
Core

Rank the 30 products by the reviews in data/reviews.csv.

  1. Stream the file with a generator that yields (product_id, product, rating, review_date). The texts contain line breaks, so use the csv module.
  2. In one pass, group the ratings and the review dates per product with dicts.
  3. Print the 3 best products by mean rating (ties: more reviews first, then the id) and the 3 worst with heapq.nsmallest.
  4. A product manager asks about the 3 worst products: when was each one’s last review on or before 2024-06-30, and how many reviews came later? Answer with bisect_right on each product’s sorted dates.
  5. Merge the 30 sorted date lists into one sorted list with heapq.merge, and print the month with the most reviews, with itertools.groupby.
Expected output
3,000 reviews of 30 products
best P018 Adjustable Dumbbells 4.28 (53)
best P021 Harbor Lane Mysteries 4.21 (115)
best P008 Chef's Knife Set 4.15 (117)
worst P007 Robot Vacuum 3.09 (67)
worst P013 Slim Fit Jeans 3.34 (131)
worst P005 Smartwatch Series 5 3.47 (106)
last review on or before 2024-06-30, and reviews after it:
P007 2024-06-26 37 later
P013 2024-06-20 29 later
P005 2024-06-30 43 later
busiest month: 2024-06 with 153 reviews
Starter
import csv
import heapq
from bisect import bisect_right
from collections.abc import Iterator
from itertools import groupby
def read_reviews(path: str) -> Iterator[tuple[str, str, int, str]]:
... # TODO: yield (product_id, product, rating, review_date)
# TODO: group ratings and dates per product, rank, query with bisect_right
# TODO: merge the date lists and find the busiest month
Hint 1

ratings.setdefault(product_id, []).append(rating) groups in one pass. The sort key (-mean, -count, product_id) sorts by mean down, count down and id up. The file is sorted by date, so each product’s list of dates is sorted too.

Hint 2

bisect_right(dates, cutoff) is the number of dates that are <= the cutoff. The last of them sits one position to the left. heapq.merge(*lists) yields the items of sorted lists in sorted order.

Solution
import csv
import heapq
from bisect import bisect_right
from collections.abc import Iterator
from itertools import groupby
def read_reviews(path: str) -> Iterator[tuple[str, str, int, str]]:
"""Yield (product_id, product, rating, review_date) per review."""
with open(path, encoding="utf-8", newline="") as file:
for row in csv.DictReader(file):
yield (
row["product_id"],
row["product"],
int(row["rating"]),
row["review_date"],
)
ratings: dict[str, list[int]] = {}
review_dates: dict[str, list[str]] = {}
names: dict[str, str] = {}
for product_id, product, rating, review_date in read_reviews("data/reviews.csv"):
ratings.setdefault(product_id, []).append(rating)
review_dates.setdefault(product_id, []).append(review_date)
names[product_id] = product
summary = [
(pid, sum(values) / len(values), len(values)) for pid, values in ratings.items()
]
ranked = sorted(summary, key=lambda item: (-item[1], -item[2], item[0]))
print(f"{sum(len(v) for v in ratings.values()):,} reviews of {len(ranked)} products")
for pid, mean, count in ranked[:3]:
print(f" best {pid} {names[pid]:<22} {mean:.2f} ({count})")
worst = heapq.nsmallest(3, summary, key=lambda item: item[1])
for pid, mean, count in worst:
print(f" worst {pid} {names[pid]:<22} {mean:.2f} ({count})")
cutoff = "2024-06-30"
print(f"last review on or before {cutoff}, and reviews after it:")
for pid, _, _ in worst:
dates = review_dates[pid]
cut = bisect_right(dates, cutoff)
print(f" {pid} {dates[cut - 1]} {len(dates) - cut:>3} later")
all_dates = list(heapq.merge(*review_dates.values())) # merge sorted lists
per_month = {m: len(list(run)) for m, run in groupby(all_dates, lambda d: d[:7])}
busiest = max(per_month, key=per_month.__getitem__)
print(f"busiest month: {busiest} with {per_month[busiest]} reviews")
assert all(dates == sorted(dates) for dates in review_dates.values())
assert all_dates == sorted(all_dates)
assert len(per_month) == 24
assert sum(per_month.values()) == 3000
Output
3,000 reviews of 30 products
best P018 Adjustable Dumbbells 4.28 (53)
best P021 Harbor Lane Mysteries 4.21 (115)
best P008 Chef's Knife Set 4.15 (117)
worst P007 Robot Vacuum 3.09 (67)
worst P013 Slim Fit Jeans 3.34 (131)
worst P005 Smartwatch Series 5 3.47 (106)
last review on or before 2024-06-30, and reviews after it:
P007 2024-06-26 37 later
P013 2024-06-20 29 later
P005 2024-06-30 43 later
busiest month: 2024-06 with 153 reviews

How it works:

  1. The generator reads one row at a time, and csv.DictReader handles the quoted line breaks inside the texts (module 10). The loop fills three dicts in one pass. The data dictionary gives the same means.
  2. setdefault groups without an if key in dict check (module 13). A hash map turns grouping into one O(n)O(n) pass (module 17).
  3. A tuple key sorts by several keys at once: negate the numbers that you want in descending order. heapq.nsmallest keeps only 3 items and costs O(nlog⁡k)O(n \log k).
  4. bisect_right finds the insertion point after every date equal to the cutoff, in O(log⁡n)O(\log n). That is why P005’s review on 2024-06-30 itself counts as “on or before”. bisect_left would exclude it.
  5. heapq.merge combines the 30 sorted lists without a full sort: it keeps one item per list in a heap of 30. The assert checks that the result is sorted.
  6. groupby groups runs of equal keys, so it needs sorted data. Each month is one run of the merged dates. June 2024 is the busiest month.
  7. With exact means, P021 (4.21) ranks above P008 (4.15). The API of P2-05 rounds both to 4.2, which makes them tie. Rounding before ranking loses information.

P2-10 · Fix the bugs that mypy finds: house rankers

Section titled “P2-10 · Fix the bugs that mypy finds: house rankers”
Core

Fix the bugs: rankers_bad.py ranks the houses of data/houses.csv with small scorer classes that share a Ranker protocol. It crashes at runtime on the first blank school rating. mypy finds this bug and two more. One makes a call that silently does the wrong thing. The other would crash later, but the first crash hides it:

rankers_bad.py
"""Rank houses by simple value scores (with type bugs)."""
import csv
import heapq
from collections.abc import Callable, Iterable
from typing import Literal, Protocol, TypedDict
type Order = Literal["high", "low"]
class House(TypedDict):
house_id: str
neighborhood: str
sqft: int
price: int
school_rating: int | None
class Ranker(Protocol):
name: str
def score(self, house: House) -> float: ...
class PricePerSqft:
name = "price per sqft"
def score(self, house: House) -> float:
return house["price"] / house["sqft"]
class SchoolPerPrice:
name = "school rating per 100k"
def score(self, house: House) -> float:
return house["school_rating"] / house["price"] * 100_000
class Largest:
title = "largest"
def score(self, house: House) -> float:
return house["sqft"]
def load(path: str) -> list[House]:
with open(path, encoding="utf-8", newline="") as file:
return [
{
"house_id": row["house_id"],
"neighborhood": row["neighborhood"],
"sqft": int(row["sqft"]),
"price": int(row["price"]),
"school_rating": (
int(row["school_rating"]) if row["school_rating"] else None
),
}
for row in csv.DictReader(file)
]
def top_k[T](
items: Iterable[T], k: int, key: Callable[[T], float], order: Order = "high"
) -> list[T]:
"""Return the k items with the highest (or lowest) key, in O(n log k)."""
if order == "high":
return heapq.nlargest(k, items, key=key)
return heapq.nsmallest(k, items, key=key)
def show(ranker: Ranker, houses: list[House], order: Order = "high") -> None:
print(f"{ranker.name} ({order}):")
for house in top_k(houses, 3, ranker.score, order):
print(
f" {house['house_id']} {house['neighborhood']:<12}"
f" {ranker.score(house):>8.1f}"
)
if __name__ == "__main__":
houses = load("data/houses.csv")
show(PricePerSqft(), houses, order="lowest")
show(SchoolPerPrice(), houses)
show(Largest(), houses)
Terminal
mypy --pretty rankers_bad.py
Output
rankers_bad.py:36: error: Unsupported operand types for / ("None" and "int") [operator]
return house["school_rating"] / house["price"] * 100_000
^
rankers_bad.py:36: note: Left operand is of type "int | None"
rankers_bad.py:82: error: Argument "order" to "show" has incompatible type "Literal['lowest']";
expected "Literal['high', 'low']" [arg-type]
show(PricePerSqft(), houses, order="lowest")
^~~~~~~~
rankers_bad.py:84: error: Argument 1 to "show" has incompatible type "Largest"; expected "Ranker"
[arg-type]
show(Largest(), houses)
^~~~~~~~~
rankers_bad.py:84: note: "Largest" is missing following "Ranker" protocol member:
rankers_bad.py:84: note: name
Found 3 errors in 1 file (checked 1 source file)

Fix the three errors in a copy, rankers.py. A house without a school rating scores 0. The fixed file must pass mypy --strict, ruff check and ruff format --check, and print:

Expected output
price per sqft (low):
H1144 Cedar Park 60.3
H0457 Cedar Park 72.5
H1216 Cedar Park 79.0
school rating per 100k (high):
H2368 Westfield 5.3
H0957 Old Town 5.1
H0476 Maple Grove 4.9
largest (high):
H2921 Lakeview 5710.0
H0023 Oak Hill 5690.0
H2752 Oak Hill 5180.0

Then explain which of the three errors crash at runtime, and what the other one does instead.

Starter
# Copy rankers_bad.py to rankers.py.
# TODO: fix the three errors that mypy reports
Hint 1

Read each report as file, line, message and error code. The note: lines under an error tell you the inferred type and the missing protocol member.

Hint 2

After if house["school_rating"] is None: return 0.0, mypy knows that the value is an int. A protocol matches by structure: Largest needs an attribute called name, not title. It does not need to inherit from Ranker.

Solution
rankers.py
"""Rank houses by simple value scores. Check with: mypy --strict rankers.py"""
import csv
import heapq
from collections.abc import Callable, Iterable
from typing import Literal, Protocol, TypedDict
type Order = Literal["high", "low"]
class House(TypedDict):
house_id: str
neighborhood: str
sqft: int
price: int
school_rating: int | None
class Ranker(Protocol):
name: str
def score(self, house: House) -> float: ...
class PricePerSqft:
name = "price per sqft"
def score(self, house: House) -> float:
return house["price"] / house["sqft"]
class SchoolPerPrice:
name = "school rating per 100k"
def score(self, house: House) -> float:
if house["school_rating"] is None:
return 0.0
return house["school_rating"] / house["price"] * 100_000
class Largest:
name = "largest"
def score(self, house: House) -> float:
return house["sqft"]
def load(path: str) -> list[House]:
with open(path, encoding="utf-8", newline="") as file:
return [
{
"house_id": row["house_id"],
"neighborhood": row["neighborhood"],
"sqft": int(row["sqft"]),
"price": int(row["price"]),
"school_rating": (
int(row["school_rating"]) if row["school_rating"] else None
),
}
for row in csv.DictReader(file)
]
def top_k[T](
items: Iterable[T], k: int, key: Callable[[T], float], order: Order = "high"
) -> list[T]:
"""Return the k items with the highest (or lowest) key, in O(n log k)."""
if order == "high":
return heapq.nlargest(k, items, key=key)
return heapq.nsmallest(k, items, key=key)
def show(ranker: Ranker, houses: list[House], order: Order = "high") -> None:
print(f"{ranker.name} ({order}):")
for house in top_k(houses, 3, ranker.score, order):
print(
f" {house['house_id']} {house['neighborhood']:<12}"
f" {ranker.score(house):>8.1f}"
)
if __name__ == "__main__":
houses = load("data/houses.csv")
show(PricePerSqft(), houses, order="low")
show(SchoolPerPrice(), houses)
show(Largest(), houses)
rated = [house for house in houses if house["school_rating"] is not None]
assert len(houses) == 3000
assert len(rated) == 2910
Output
price per sqft (low):
H1144 Cedar Park 60.3
H0457 Cedar Park 72.5
H1216 Cedar Park 79.0
school rating per 100k (high):
H2368 Westfield 5.3
H0957 Old Town 5.1
H0476 Maple Grove 4.9
largest (high):
H2921 Lakeview 5710.0
H0023 Oak Hill 5690.0
H2752 Oak Hill 5180.0
Terminal
mypy --strict rankers.py
ruff check rankers.py
ruff format --check rankers.py
Output
Success: no issues found in 1 source file
All checks passed!
1 file already formatted

How it works:

  1. int | None without a check (module 12): 90 houses have a blank school rating, so load() stores None. Dividing None raises TypeError at runtime. The is None check narrows the type, and mypy accepts the division after it.
  2. A value outside the Literal: Python does not check hints at runtime. top_k() tests only order == "high", so "lowest" silently falls into the nsmallest branch and happens to work. A typo such as "hihg" would also give the lowest houses, without any error. The Literal alias lets mypy catch it before the script runs.
  3. Protocol mismatch: Ranker asks for a name attribute and a score() method. Largest had title, so show() would crash with AttributeError when it printed the heading. Renaming the attribute makes the class match, without inheritance (structural typing).
  4. top_k[T] is generic: mypy knows that it returns list[House] for a list of houses (module 12). heapq.nlargest and nsmallest keep only k items, O(nlog⁡k)O(n \log k) (module 17).
  5. ruff check finds style and bug patterns, ruff format --check reports layout that differs from the standard format, and mypy finds type errors (module 13). They check different things, so a clean project runs all three.
  6. H0957 is in the top 3 by school rating per price because it is one of the 8 price outliers of the data dictionary: its price was deflated to 117,500. Check outliers before you trust a ranking.

P2-11 · Choose and justify: one tool per job

Section titled “P2-11 · Choose and justify: one tool per job”
Core

Choose a tool and justify it: for each job below, name the data structure, library function or kind of concurrency you would use, its cost in big-O notation, and one sentence of reason. Then do jobs 1 to 4 in code on the course data.

  1. Check the customer_id of all 20,228 lines of data/sales.csv against the 5,000 ids of data/customers.csv.
  2. Report the 3 sales lines with the highest revenue.
  3. A gift guide wants to know how many pairs of two different products of data/products.csv cost at most 50 together. Count them without testing all 435 pairs, and count your steps.
  4. Find the city of the store of every sales line with a function store_city(store_id) that reads data/stores.csv. It gets 20,228 calls, but only 12 different ids. Print how many calls it got and how many times it read the file.
  5. Keep the last 6 valid readings of a sensor stream for a rolling mean.
  6. Download 30 API pages. Each request waits about 200 ms for the server.
  7. Run 2,000 bootstrap resamples of a pure-Python statistic on 5,000 customers.
Expected output
unknown customer ids: 0 of 20,228 lines
O001531 55-inch 4K Smart TV 5,196.00
O006934 14-inch Ultrabook Laptop 4,596.00
O011849 14-inch Ultrabook Laptop 4,596.00
product pairs within 50: 41 (29 pointer steps)
store_city calls: 20,228, file reads: 12
Starter
import csv
with open("data/customers.csv", encoding="utf-8", newline="") as file:
customers = list(csv.DictReader(file))
with open("data/sales.csv", encoding="utf-8", newline="") as file:
sales = list(csv.DictReader(file))
with open("data/products.csv", encoding="utf-8", newline="") as file:
prices = sorted(float(row["unit_price"]) for row in csv.DictReader(file))
def store_city(store_id: str) -> str:
with open("data/stores.csv", encoding="utf-8", newline="") as file:
for row in csv.DictReader(file):
if row["store_id"] == store_id:
return row["city"]
raise KeyError(store_id)
# TODO: jobs 1 to 4 in code
# TODO: jobs 5 to 7, write your choice and reason as comments
Hint 1

Ask what each job does many times: a membership test, a “keep the best k”, a pair test, a call with the same argument. Each operation has a structure or a tool that makes it cheap.

Hint 2

For job 3, put one pointer at the cheapest price and one at the most expensive. If the two fit the budget, the cheap one fits with every price between them. If they do not fit, the expensive one fits with nothing that is left. Jobs 6 and 7 differ in what the time is spent on: waiting or computing. Remember what the GIL allows.

Solution
import csv
import heapq
from functools import cache
with open("data/customers.csv", encoding="utf-8", newline="") as file:
known_ids = {row["customer_id"] for row in csv.DictReader(file)}
with open("data/sales.csv", encoding="utf-8", newline="") as file:
sales = list(csv.DictReader(file))
with open("data/products.csv", encoding="utf-8", newline="") as file:
prices = sorted(float(row["unit_price"]) for row in csv.DictReader(file))
# Job 1: membership tests -> a set, O(1) per test, O(n) in total
unknown = sum(1 for row in sales if row["customer_id"] not in known_ids)
print(f"unknown customer ids: {unknown} of {len(sales):,} lines")
# Job 2: top 3 of 20,228 lines -> heapq.nlargest, O(n log k)
top = heapq.nlargest(3, sales, key=lambda row: float(row["revenue"]))
for row in top:
print(f" {row['order_id']} {row['product']:<26} {float(row['revenue']):>9,.2f}")
# Job 3: pairs within a budget -> sorted prices + two pointers, O(n) after the sort
budget = 50.0
left, right, pairs, steps = 0, len(prices) - 1, 0, 0
while left < right:
steps += 1
if prices[left] + prices[right] <= budget:
pairs += right - left # prices[left] fits with every price up to right
left += 1
else:
right -= 1
print(f"product pairs within {budget:.0f}: {pairs} ({steps} pointer steps)")
# Job 4: repeated calls with few distinct arguments -> cache, O(1) per hit
@cache
def store_city(store_id: str) -> str:
with open("data/stores.csv", encoding="utf-8", newline="") as file:
for row in csv.DictReader(file):
if row["store_id"] == store_id:
return row["city"]
raise KeyError(store_id)
cities = [store_city(row["store_id"]) for row in sales]
info = store_city.cache_info()
print(f"store_city calls: {info.hits + info.misses:,}, file reads: {info.misses}")
# Job 5: last 6 readings -> deque(maxlen=6); O(1) per new reading
# Job 6: I/O-bound -> ThreadPoolExecutor or asyncio; the waits overlap
# Job 7: CPU-bound pure Python -> ProcessPoolExecutor; threads share one GIL
brute = sum(
1
for i in range(len(prices))
for j in range(i + 1, len(prices))
if prices[i] + prices[j] <= budget
)
assert unknown == 0
assert pairs == brute
assert info.misses == 12
assert cities.count("New York") == 2541
Output
unknown customer ids: 0 of 20,228 lines
O001531 55-inch 4K Smart TV 5,196.00
O006934 14-inch Ultrabook Laptop 4,596.00
O011849 14-inch Ultrabook Laptop 4,596.00
product pairs within 50: 41 (29 pointer steps)
store_city calls: 20,228, file reads: 12
Job Choice Cost Reason
1 set of known ids O(1)O(1) per test x in list scans up to 5,000 ids per line: about 100 million comparisons in the worst case.
2 heapq.nlargest(3, ...) O(nlog⁡k)O(n \log k) It keeps only 3 items in a heap. A full sort costs O(nlog⁡n)O(n \log n) to keep 3.
3 sort + two pointers O(nlog⁡n)O(n \log n) sort, then O(n)O(n) Each step moves one pointer, so 30 prices need 29 steps instead of 435 pair tests.
4 functools.cache O(1)O(1) per repeated call The function is pure and has 12 distinct inputs, so 12 file reads replace 20,228.
5 deque(maxlen=6) O(1)O(1) per reading The deque drops the oldest value by itself. list.pop(0) shifts every item.
6 threads or asyncio about 30 waits divided by the number of workers The time is waiting. The GIL is released while a thread waits for the network.
7 process pool CPU time divided by the cores Pure Python holds the GIL, so threads would run one at a time. Processes use all cores.

How it works:

  1. Each choice follows the operation that runs most often (modules 15 and 17). The data structure decides the speed before any micro-tuning.
  2. heapq.nlargest returns ties in input order, like a stable sort: both laptop lines have revenue 4,596.00, and the earlier order comes first.
  3. Two pointers on sorted data: when prices[left] + prices[right] fits the budget, every price between the two pointers fits with prices[left] too, so the loop adds right - left pairs at once and moves left. Otherwise prices[right] is too expensive for every remaining partner, and right moves. The assert checks the 41 pairs against the brute-force count over all 435 pairs.
  4. @cache (an lru_cache without a size limit) stores each result under its arguments (module 11). cache_info() reports 12 misses (one file read per store) and 20,216 hits. A cache is safe here because the function always returns the same city for the same id.

P2-12 · Predict, then rewrite: context managers, a generator and two decorators

Section titled “P2-12 · Predict, then rewrite: context managers, a generator and two decorators”
Challenge

Predict the output, then rewrite: load() is wrapped in two decorators, opens two context managers through an ExitStack, stops a generator early and raises an error.

  1. Write down every line it prints, in order, then run it.
  2. Rewrite the two context managers in the other style: Step as a generator function step(name) with @contextmanager, and section as a class Section with __enter__ and __exit__. Use them in load(). The script must print the same 14 lines. Capture them with redirect_stdout to check.

Acceptance criteria:

  • Write your prediction for all 14 lines before you run the code.
  • Your prediction matches the Output in the solution, line by line.
  • You can explain why after with is printed, and in which order the two context managers exit.
  • Your rewrite prints the same 14 lines, and step() suppresses only KeyError.
Starter
import functools
from collections.abc import Callable, Iterator
from contextlib import ExitStack, contextmanager, suppress
from types import TracebackType
class Step:
def __init__(self, name: str) -> None:
self.name = name
def __enter__(self) -> str:
print(f"enter {self.name}")
return self.name.upper()
def __exit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> bool:
print(f"exit {self.name}: {exc_type.__name__ if exc_type else 'ok'}")
return exc_type is KeyError
@contextmanager
def section(title: str) -> Iterator[int]:
print(f"[{title}")
try:
yield len(title)
finally:
print(f"{title}]")
def rows() -> Iterator[int]:
try:
for n in range(1, 5):
print(f" row {n}")
yield n
finally:
print(" rows closed")
def tag(label: str) -> Callable[[Callable[[], str]], Callable[[], str]]:
def decorate(func: Callable[[], str]) -> Callable[[], str]:
@functools.wraps(func)
def wrapper() -> str:
print(f"{label} in")
result = func()
print(f"{label} out")
return result
return wrapper
return decorate
@tag("outer")
@tag("inner")
def load() -> str:
with ExitStack() as stack:
name = stack.enter_context(Step("load"))
width = stack.enter_context(section("csv"))
print(name, width)
stream = rows()
for n in stream:
if n == 2:
break
with suppress(ValueError):
int("n/a")
print("never printed")
stream.close()
raise KeyError("store")
print("after with")
return load.__name__
print(load())
# TODO: write your prediction for each line before you run it
Hint 1

Stacked decorators apply bottom-up and run top-down: the outer wrapper starts first and finishes last. enter_context() returns what __enter__ returns, or what the generator of a @contextmanager yields.

Hint 2

An ExitStack exits its managers in reverse order. A true return value from __exit__ suppresses the exception. close() on a paused generator runs its finally block. suppress(ValueError) skips the rest of its own with block.

Hint 3

In a @contextmanager generator, an exception of the with block is raised at the yield. Catch it there and do not re-raise it, and the exception is suppressed. An __exit__ that returns None never suppresses.

Solution
import functools
from collections.abc import Callable, Iterator
from contextlib import ExitStack, contextmanager, suppress
from types import TracebackType
class Step:
def __init__(self, name: str) -> None:
self.name = name
def __enter__(self) -> str:
print(f"enter {self.name}")
return self.name.upper()
def __exit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> bool:
print(f"exit {self.name}: {exc_type.__name__ if exc_type else 'ok'}")
return exc_type is KeyError
@contextmanager
def section(title: str) -> Iterator[int]:
print(f"[{title}")
try:
yield len(title)
finally:
print(f"{title}]")
def rows() -> Iterator[int]:
try:
for n in range(1, 5):
print(f" row {n}")
yield n
finally:
print(" rows closed")
def tag(label: str) -> Callable[[Callable[[], str]], Callable[[], str]]:
def decorate(func: Callable[[], str]) -> Callable[[], str]:
@functools.wraps(func)
def wrapper() -> str:
print(f"{label} in")
result = func()
print(f"{label} out")
return result
return wrapper
return decorate
@tag("outer")
@tag("inner")
def load() -> str:
with ExitStack() as stack:
name = stack.enter_context(Step("load"))
width = stack.enter_context(section("csv"))
print(name, width)
stream = rows()
for n in stream:
if n == 2:
break
with suppress(ValueError):
int("n/a")
print("never printed")
stream.close()
raise KeyError("store")
print("after with")
return load.__name__
print(load())
assert load.__name__ == "load"
assert load.__wrapped__.__wrapped__.__name__ == "load"
Output
outer in
inner in
enter load
[csv
LOAD 3
row 1
row 2
rows closed
csv]
exit load: KeyError
after with
inner out
outer out
load

The rewrite reuses rows() and tag() from above:

import io
from contextlib import redirect_stdout
@contextmanager
def step(name: str) -> Iterator[str]:
print(f"enter {name}")
try:
yield name.upper()
except KeyError:
print(f"exit {name}: KeyError") # not re-raised: the error is suppressed
except BaseException as error:
print(f"exit {name}: {type(error).__name__}")
raise
else:
print(f"exit {name}: ok")
class Section:
def __init__(self, title: str) -> None:
self.title = title
def __enter__(self) -> int:
print(f"[{self.title}")
return len(self.title)
def __exit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> None:
print(f"{self.title}]") # returns None: never suppresses
@tag("outer")
@tag("inner")
def load() -> str:
with ExitStack() as stack:
name = stack.enter_context(step("load"))
width = stack.enter_context(Section("csv"))
print(name, width)
stream = rows()
for n in stream:
if n == 2:
break
with suppress(ValueError):
int("n/a")
print("never printed")
stream.close()
raise KeyError("store")
print("after with")
return load.__name__
with redirect_stdout(io.StringIO()) as rewritten:
print(load())
print(rewritten.getvalue(), end="")
assert rewritten.getvalue().count("\n") == 14
assert "exit load: KeyError" in rewritten.getvalue()
Output
outer in
inner in
enter load
[csv
LOAD 3
row 1
row 2
rows closed
csv]
exit load: KeyError
after with
inner out
outer out
load

How it works:

  1. @tag("outer") wraps the result of @tag("inner"). A call enters the outer wrapper first, so outer in comes before inner in, and inner out comes before outer out (module 11).

  2. enter_context(Step("load")) prints enter load and returns "LOAD". enter_context(section("csv")) runs the generator up to its yield, prints [csv and returns len("csv"), which is 3.

  3. The for loop stops at break while the generator is paused at its second yield (module 10). stream.close() raises GeneratorExit inside it, so its finally prints rows closed. row 3 is never printed.

  4. int("n/a") raises ValueError. suppress catches it and skips the rest of its block, so never printed is never printed.

  5. KeyError leaves the with block. The ExitStack exits in reverse order: first section, whose finally prints csv], then Step, which prints exit load: KeyError and returns True. A true return value suppresses the exception, so the function goes on with after with.

  6. Thanks to functools.wraps, the global name load (the outer wrapper) still has the name load. __wrapped__ leads back through both layers to the original function.

  7. In the rewrite, step() sees the KeyError at its yield. It prints the exit line and does not re-raise, which suppresses the error, like a true return value of __exit__. Any other exception is re-raised after its line. Section.__exit__ returns None, so it never suppresses. Both styles give the same 14 lines.

P2-13 · An async product client with a typed retry decorator

Section titled “P2-13 · An async product client with a typed retry decorator”
Challenge

Write an async client that fetches the 30 products one by one from GET /products/{id}, plus the unknown id P031. The starter gives a fake server as an async httpx.MockTransport handler. The server needs an API key. It answers 503 twice for P013, 429 with Retry-After: 3 once for P020 and 404 for P031. It also answers 429 without Retry-After (“busy”) when more than 4 requests are in flight. Requirements:

  1. Read the key from the environment variable SHOP_API_KEY. The script sets it for this exercise; in real code it comes from your shell or a git-ignored .env file. Print only its first 7 characters and its length.
  2. Write a decorator factory retry_async(attempts, sleep) for async functions, typed with [**P, R]. It retries only on 429 and 5xx, waits as long as Retry-After says (or 1, 2, 4 … seconds without the header), and re-raises after the last attempt. Inject a fake sleep that records the waits, so the script never really waits.
  3. Fetch all 31 ids with one httpx.AsyncClient and asyncio.gather. Limit the requests in flight with an asyncio.Semaphore, so that the server never answers “busy”. Keep the results in the order of the ids, and turn a failed product into a status line instead of a crash.
  4. Print the number of products, the units in stock, the sorted waits, the number of requests and the number of busy answers.
Expected output
key: sk-test... (16 chars)
P031: HTTP 404
fetched 30 products, P001 to P030
units in stock: 3,165
waits: [1.0, 2.0, 3.0], requests: 34, busy: 0
Starter
import asyncio
import json
import os
from collections import Counter
from pathlib import Path
import httpx
os.environ["SHOP_API_KEY"] = "sk-test-4f9a2c71" # stands in for your shell or .env
# --- the fake API (given) ---------------------------------------------------
PRODUCTS = {
item["id"]: item
for page in (1, 2, 3)
for item in json.loads(
Path(f"data/api/products_page_{page}.json").read_text(encoding="utf-8")
)["data"]
}
calls: Counter[str] = Counter()
server = {"in_flight": 0, "busy": 0}
async def handler(request: httpx.Request) -> httpx.Response:
"""GET /products/{id}. Flaky on P013, rate-limits P020, busy above 4."""
if request.headers.get("Authorization") != "Bearer sk-test-4f9a2c71":
return httpx.Response(401, json={"error": "unauthorized"})
product_id = request.url.path.rsplit("/", 1)[-1]
calls[product_id] += 1
if server["in_flight"] >= 4:
server["busy"] += 1
return httpx.Response(429, json={"error": "too many requests at once"})
server["in_flight"] += 1
await asyncio.sleep(0.01)
server["in_flight"] -= 1
if product_id == "P013" and calls[product_id] <= 2:
return httpx.Response(503, json={"error": "unavailable"})
if product_id == "P020" and calls[product_id] == 1:
return httpx.Response(429, headers={"Retry-After": "3"})
if product_id not in PRODUCTS:
return httpx.Response(404, json={"error": "not_found"})
return httpx.Response(200, json=PRODUCTS[product_id])
# --- your client --------------------------------------------------------------
# TODO: waits list and an async fake_sleep(seconds) that records them
# TODO: retry_async(attempts, sleep) for async functions
# TODO: get_product(client, limit, product_id), decorated with retry_async
# TODO: fetch_products(product_ids, key) with AsyncClient, a Semaphore and gather
# TODO: print the report
Hint 1

Pass the key once, as a client header: httpx.AsyncClient(headers={"Authorization": f"Bearer {key}"}, transport=httpx.MockTransport(handler), base_url=...). Hold the semaphore only around the request: async with limit: response = await client.get(...).

Hint 2

asyncio.gather(*tasks, return_exceptions=True) returns the results in argument order, with exceptions as values. The wrapper of the retry decorator is an async def that awaits func(*args, **kwargs) in a loop. Type the decorated function as Callable[P, Awaitable[R]].

Hint 3

A 404 cannot be fixed by retrying. The transient statuses are 429 and 500 to 599. P013 needs 3 attempts, so attempts must be at least 3.

Solution
import asyncio
import functools
import json
import os
from collections import Counter
from collections.abc import Awaitable, Callable
from pathlib import Path
from typing import Any
import httpx
os.environ["SHOP_API_KEY"] = "sk-test-4f9a2c71" # stands in for your shell or .env
# --- the fake API (given) ---------------------------------------------------
PRODUCTS = {
item["id"]: item
for page in (1, 2, 3)
for item in json.loads(
Path(f"data/api/products_page_{page}.json").read_text(encoding="utf-8")
)["data"]
}
calls: Counter[str] = Counter()
server = {"in_flight": 0, "busy": 0}
async def handler(request: httpx.Request) -> httpx.Response:
"""GET /products/{id}. Flaky on P013, rate-limits P020, busy above 4."""
if request.headers.get("Authorization") != "Bearer sk-test-4f9a2c71":
return httpx.Response(401, json={"error": "unauthorized"})
product_id = request.url.path.rsplit("/", 1)[-1]
calls[product_id] += 1
if server["in_flight"] >= 4:
server["busy"] += 1
return httpx.Response(429, json={"error": "too many requests at once"})
server["in_flight"] += 1
await asyncio.sleep(0.01)
server["in_flight"] -= 1
if product_id == "P013" and calls[product_id] <= 2:
return httpx.Response(503, json={"error": "unavailable"})
if product_id == "P020" and calls[product_id] == 1:
return httpx.Response(429, headers={"Retry-After": "3"})
if product_id not in PRODUCTS:
return httpx.Response(404, json={"error": "not_found"})
return httpx.Response(200, json=PRODUCTS[product_id])
# --- your client --------------------------------------------------------------
waits: list[float] = []
async def fake_sleep(seconds: float) -> None:
waits.append(seconds)
def retry_async[**P, R](
attempts: int, sleep: Callable[[float], Awaitable[None]] = asyncio.sleep
) -> Callable[[Callable[P, Awaitable[R]]], Callable[P, Awaitable[R]]]:
"""Retry on 429 and 5xx, waiting Retry-After seconds or 1, 2, 4..."""
def decorate(func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]:
@functools.wraps(func)
async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
for attempt in range(1, attempts + 1):
try:
return await func(*args, **kwargs)
except httpx.HTTPStatusError as error:
status = error.response.status_code
transient = status == 429 or status >= 500
if not transient or attempt == attempts:
raise
header = error.response.headers.get("Retry-After")
await sleep(float(header) if header else 2.0 ** (attempt - 1))
raise AssertionError("unreachable")
return wrapper
return decorate
@retry_async(attempts=4, sleep=fake_sleep)
async def get_product(
client: httpx.AsyncClient, limit: asyncio.Semaphore, product_id: str
) -> dict[str, Any]:
async with limit:
response = await client.get(f"/products/{product_id}")
response.raise_for_status()
product: dict[str, Any] = response.json()
return product
async def fetch_products(
product_ids: list[str], key: str
) -> list[dict[str, Any] | BaseException]:
limit = asyncio.Semaphore(4)
async with httpx.AsyncClient(
base_url="https://api.example.com/v1",
headers={"Authorization": f"Bearer {key}"},
transport=httpx.MockTransport(handler),
) as client:
tasks = [get_product(client, limit, pid) for pid in product_ids]
return await asyncio.gather(*tasks, return_exceptions=True)
key = os.environ["SHOP_API_KEY"]
print(f"key: {key[:7]}... ({len(key)} chars)")
product_ids = [f"P{n:03d}" for n in range(1, 32)]
results = asyncio.run(fetch_products(product_ids, key))
found: dict[str, dict[str, Any]] = {}
for product_id, result in zip(product_ids, results, strict=True):
if isinstance(result, httpx.HTTPStatusError):
print(f"{product_id}: HTTP {result.response.status_code}")
elif isinstance(result, BaseException):
raise result
else:
found[product_id] = result
print(f"fetched {len(found)} products, {min(found)} to {max(found)}")
print(f"units in stock: {sum(p['stock'] for p in found.values()):,}")
print(f"waits: {sorted(waits)}, requests: {calls.total()}, busy: {server['busy']}")
assert list(found) == product_ids[:30]
assert calls["P013"] == 3 and calls["P020"] == 2
assert server["busy"] == 0
Output
key: sk-test... (16 chars)
P031: HTTP 404
fetched 30 products, P001 to P030
units in stock: 3,165
waits: [1.0, 2.0, 3.0], requests: 34, busy: 0

How it works:

  1. The key lives in the environment, and the script prints only a short prefix and the length (module 16). The key goes into one client header, so no request can forget it.
  2. retry_async has three levels: settings, function, call (module 11). Its typed form Callable[P, Awaitable[R]] keeps the real signature of get_product for a type checker (module 12).
  3. P013 fails twice with 503, without a Retry-After header, so the waits are 1 and 2 seconds of exponential backoff. P020 gets 429 with Retry-After: 3, so it waits 3 seconds. The fake sleep records the waits instead of sleeping. The waits are printed sorted, because concurrent retries may record them in any order.
  4. 31 ids cost 34 requests: 2 extra for P013 and 1 for P020. 404 is not transient, so P031 is re-raised at once and becomes a status line.
  5. gather runs the 31 coroutines concurrently in one thread and returns the results in the order of the ids, not in finish order (module 15). Semaphore(4) lets only 4 coroutines into the request at a time, so the server never answers “busy”. With Semaphore(5), the fifth request is refused, and the instant fake retries pile up into more than 100 requests.
  6. The semaphore is released before the retry waits. A waiting retry therefore does not block a slot that other products could use.
  7. This server sends Retry-After in seconds only. The header may also hold an HTTP date (Wed, 21 Oct 2026 07:28:00 GMT), where float(header) raises ValueError. Real code must parse both forms, for example with email.utils.parsedate_to_datetime() for the date.

P2-14 · Campaign days from web traffic in one pass

Section titled “P2-14 · Campaign days from web traffic in one pass”
Challenge

The marketing team ran 7 campaigns between 2022 and 2024 (see data/web_traffic.csv in the data dictionary). Find them in the visits alone: a day is a spike when its visits are more than 1.5 times the mean of the 7 valid days before it.

  1. Write a re-iterable class TrafficLog(path) whose __iter__ is a generator of (date, visits) tuples. A blank visits cell gives None (EAFP).
  2. Write two detectors that yield (date, visits, is_spike) for each day that has a full window, and skip the blank days. flags_naive() is a generator that keeps a list and sums the whole window every day. FastFlags(days, window, factor) is an iterator class with __iter__ and __next__, which keeps a deque and a running total. Check that both give the same flags.
  3. Group the consecutive spike days with itertools.groupby and print each campaign: its first day, its number of spike days and its peak visits.
  4. Count the window values that each version reads per day (naive: the whole window; fast: 2), for windows of 7 and 28 days, and print the totals.
Expected output
5 blank days: 2022-08-11, 2022-08-24, 2023-05-24, 2024-05-29, 2024-10-25
start days peak
2022-03-14 3 9,198
2022-09-06 2 8,906
2023-02-20 3 11,230
2023-06-12 2 12,628
2023-10-02 2 11,208
2024-04-08 2 18,385
2024-09-16 2 14,446
window 7: naive reads 7,588, fast reads 2,168
window 28: naive reads 29,764, fast reads 2,126
Starter
import csv
from collections import deque
from collections.abc import Iterable, Iterator
from itertools import groupby
from typing import Self
type Day = tuple[str, float | None]
type Flag = tuple[str, float, bool]
reads = {"naive": 0, "fast": 0}
class TrafficLog:
def __init__(self, path: str) -> None:
self.path = path
def __iter__(self) -> Iterator[Day]:
... # TODO: read the file again on every loop
def flags_naive(days: Iterable[Day], window: int, factor: float) -> Iterator[Flag]:
... # TODO: a list window; add window to reads["naive"] per flagged day
class FastFlags:
def __init__(self, days: Iterable[Day], window: int, factor: float) -> None:
... # TODO: an iterator over days, a deque and a running total
def __iter__(self) -> Self:
... # TODO
def __next__(self) -> Flag:
... # TODO: return the next flag; add 2 to reads["fast"]
# TODO: blank days, flags, campaigns with groupby, read counts for 7 and 28
Hint 1

If __iter__ contains yield, every for loop over the object gets a new generator that opens the file again. That is what makes the class re-iterable, unlike a generator, which works only once.

Hint 2

An iterator’s __iter__ returns self. __next__ keeps pulling days from self.days until it can return a flag; when next(self.days) raises StopIteration, let it end your iterator too. Once the window is full, compare today’s visits with total / window, then subtract the oldest value (popleft()), then append today’s value and add it to total.

Hint 3

groupby(flags, key=lambda flag: flag[2]) yields runs of equal is_spike values. Keep only the runs whose key is True.

Solution
import csv
from collections import deque
from collections.abc import Iterable, Iterator
from itertools import groupby
from typing import Self
type Day = tuple[str, float | None]
type Flag = tuple[str, float, bool]
reads = {"naive": 0, "fast": 0}
class TrafficLog:
"""Re-iterable: every loop reads the file again from the start."""
def __init__(self, path: str) -> None:
self.path = path
def __iter__(self) -> Iterator[Day]:
with open(self.path, encoding="utf-8", newline="") as file:
for row in csv.DictReader(file):
try:
yield row["date"], float(row["visits"])
except ValueError: # blank cell: tracking outage
yield row["date"], None
def flags_naive(days: Iterable[Day], window: int, factor: float) -> Iterator[Flag]:
recent: list[float] = []
for date, visits in days:
if visits is None:
continue
if len(recent) == window:
reads["naive"] += window
yield date, visits, visits > factor * sum(recent) / window
recent.pop(0)
recent.append(visits)
class FastFlags:
"""An iterator: a running total over a deque, O(1) work per day."""
def __init__(self, days: Iterable[Day], window: int, factor: float) -> None:
self.days = iter(days)
self.window = window
self.factor = factor
self.recent: deque[float] = deque()
self.total = 0.0
def __iter__(self) -> Self:
return self
def __next__(self) -> Flag:
while True:
date, visits = next(self.days) # StopIteration ends this iterator too
if visits is None:
continue
flag: Flag | None = None
if len(self.recent) == self.window:
reads["fast"] += 2
mean = self.total / self.window
flag = (date, visits, visits > self.factor * mean)
self.total -= self.recent.popleft()
self.recent.append(visits)
self.total += visits
if flag is not None:
return flag
log = TrafficLog("data/web_traffic.csv")
blanks = [date for date, visits in log if visits is None]
print(f"{len(blanks)} blank days: {', '.join(blanks)}")
fast = list(FastFlags(log, window=7, factor=1.5))
naive = list(flags_naive(log, window=7, factor=1.5))
assert fast == naive
print("start days peak")
campaigns: list[str] = []
for is_spike, run in groupby(fast, key=lambda flag: flag[2]):
if is_spike:
days = list(run)
peak = max(visits for _, visits, _ in days)
campaigns.append(days[0][0])
print(f"{days[0][0]} {len(days):>4} {peak:>7,.0f}")
for window in (7, 28):
reads.update(naive=0, fast=0)
for _ in flags_naive(log, window, 1.5):
pass
for _ in FastFlags(log, window, 1.5):
pass
print(
f"window {window:>2}: naive reads {reads['naive']:>6,},"
f" fast reads {reads['fast']:>5,}"
)
flags = FastFlags(log, 7, 1.5)
assert iter(flags) is flags
assert len(campaigns) == 7
assert campaigns[0] == "2022-03-14"
assert reads["naive"] == 28 * reads["fast"] // 2
Output
5 blank days: 2022-08-11, 2022-08-24, 2023-05-24, 2024-05-29, 2024-10-25
start days peak
2022-03-14 3 9,198
2022-09-06 2 8,906
2023-02-20 3 11,230
2023-06-12 2 12,628
2023-10-02 2 11,208
2024-04-08 2 18,385
2024-09-16 2 14,446
window 7: naive reads 7,588, fast reads 2,168
window 28: naive reads 29,764, fast reads 2,126

How it works:

  1. TrafficLog is looped over many times: once for the blanks, twice for the flags and four times for the counts. Each loop opens the file again, because __iter__ is a generator function (module 10). A plain generator would be empty after the first loop.
  2. The 5 blank days come back as None, and both detectors skip them. A tracking outage therefore never enters the window as 0 visits, which would lower the mean and flag false spikes on the next days (module 13).
  3. FastFlags implements the iteration protocol by hand: __iter__ returns the object itself, and __next__ returns one item or raises StopIteration (module 10). Its state (the deque and the total) lives in attributes, where a generator keeps it in local variables. Unlike TrafficLog, a FastFlags object is one-pass: a second loop over it gets nothing.
  4. The naive version reads the whole window every day: O(n⋅k)O(n \cdot k) for nn days and a window of kk. Its list.pop(0) also shifts every item. The fast version updates a running total with one subtraction and one addition: O(n)O(n), whatever the window size (modules 15 and 17). With a 28-day window, the naive version reads 14 times more values.
  5. groupby turns the stream of flags into runs. Each True run is one campaign. The 7 start dates are exactly the campaign starts of the data dictionary, and the peak of 18,385 visits on 2024-04-08 is the top day of the file.
  6. The fast version reads slightly fewer values with a window of 28 because fewer days have a full window. The comparison in step 2 proves that the optimization did not change a single flag.

Rate yourself on each skill after you finish the exercises. Base the rating on what you did without the solution.

Skill area Not yet Getting there Ready
10. Iterators and generators: lazy pipelines, itertools You load whole files into lists. You write generators, but an exhausted iterator surprises you. You build lazy pipelines, write an iterator class and a re-iterable class, and use batched, islice and groupby correctly.
11. Decorators and context managers You copy timing or retry code into each function. You write a decorator, but forget wraps or the order of stacked decorators. You write typed decorators and decorator factories, cache repeated calls, write context managers in both styles, and predict how stacked decorators, ExitStack and suppress run and exit.
12. Type hints: generics, protocols, mypy Your functions have no hints, or hints that lie. You annotate, but cannot read a mypy report. You use TypedDict, Literal, Protocol, generics and optional types, and fix code until mypy --strict passes.
13. Pythonic code: idioms, EAFP, gotchas You write index loops and flag variables. You use idioms, but a mutable default or a short-circuit trips you up. You fix the classic gotchas (mutable defaults, late binding, is for values, float ==, changing a list in its own loop), parse with EAFP, keep code clean for ruff and refactor behind a characterization check.
14. Testing with pytest You check results by printing them. You write tests, but repeat setup code and test one input each. You lay out src/ and tests/ with shared fixtures in conftest.py, write parametrized tests with IDs, use tmp_path, monkeypatch and capsys, and read coverage.
15. Performance and concurrency You guess which code is slow. You time code, but do not profile it or choose the kind of concurrency. You profile, fix the hotspot, prove the speedup with timeit, and use thread pools and asyncio with results in a fixed order.
16. APIs and web data: HTTP, JSON, HTML You read the JSON body without checking the status. You call an API, but crash on a missing page or a 429. You paginate safely, retry only transient errors with Retry-After, keep keys secret, flatten JSON, and scrape HTML with CSS selectors.
17. Algorithms and data structures You use lists for every job. You use sets and dicts, but cannot give the big-O. You choose sets, heaps, bisect, two pointers and caches by the operation, and replace an O(n⋅k)O(n \cdot k) window with O(n)O(n).

You are ready for Part 3 when you can:

  • Solve at least 10 of the 14 exercises without opening the solution, including one challenge.
  • Predict the output of P2-01 and P2-12 with at most one wrong line each.
  • Stream a file through a chain of generators, and explain when a generator is exhausted.
  • Write a decorator that keeps the name and the signature of the function it wraps, write a context manager as a class and with @contextmanager, and predict in which order stacked decorators and context managers run and exit.
  • Describe records with TypedDict and protocols, and fix the errors that mypy --strict reports.
  • Write a scraper with CSS selectors and a pytest suite in tests/, with conftest.py fixtures, parametrize, tmp_path, monkeypatch and capsys, that reaches full coverage.
  • Profile slow code, fix it with the right data structure, time it with timeit, and prove with a characterization check that the output did not change.
  • Download paginated or concurrent API data offline with httpx.MockTransport, stop on a looping next link, and handle 404, 429 and 503 correctly.
  • Spot the gotchas is versus ==, float equality and changing a list while you loop over it.
  • Give the big-O of your solution, and use bisect, heapq, two pointers, an iterator class and a sliding window where they fit.

Rated “Not yet” in a row? Review that module’s lesson and cheat sheet, redo two of its core exercises, then try the matching checkpoint exercise again. When every row reads “Getting there” or “Ready”, move on to Part 3, module 18: Classes and objects. Part 3 builds on these skills: classes generalize the protocols and re-iterable objects of this Part, and dataclasses replace many of the TypedDict records.