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:
- Work without your notes first. Read the task and the expected output, then write your code.
- Stuck for more than 10 minutes? Open one hint at a time.
- Open the solution only after a real attempt. Compare your code with it, not only your output.
- 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”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.
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
@announcedef 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 itHint 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
@announcedef 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]decorating high_readingsstartcalling high_readingscreated wrapper check 21.4 check 23.923.9 check 19.8 check 24.6True check 25.1[25.1]empty[False, False]How it works:
@announcerunsannounce(high_readings)at definition time, sodecorating ...comes beforestart(module 11).- Calling the decorated function runs the wrapper, which prints
calling .... The wrapper then calls the generator function, which only creates a generator object. Nocheckline appears yet (module 10). - The wrapper has no
@functools.wraps(func), so the name is nowwrapper. Addwrapsand the line readscreated high_readings. next()runs the body up to the firstyield: 21.4 fails the test, 23.9 passes and is returned.any()pulls items until one is true. 24.6 is the first value above 24, soany()stops there, and 25.1 is not checked yet (module 13).list()drains the rest: one more check and[25.1]. The generator is now exhausted, sonext(stream, "empty")returns the default.- Both lambdas read
limitwhen they are called, not when they are created. By then the loop has ended withlimit = 24.0, so both test23.0 > 24.0. This is the late-binding gotcha (module 13). Ruff reports it asB023; in your own code, fix it instead of keeping it. Bind the value at creation time with a default:lambda value, limit=limit: value > limitgives[True, False].
P2-02 · Fix the bugs: a typed readings summary
Section titled “P2-02 · Fix the bugs: a typed readings summary”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, Iteratorfrom 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))))(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"].
40 readings, mean 21.06, max 22.95 readings, mean 21.62, max 22.1no valid readingsfrom collections.abc import Iterable, Iteratorfrom 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, Iteratorfrom 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] == 40assert head is not None and head[0] == 5assert none_valid is None40 readings, mean 21.06, max 22.95 readings, mean 21.62, max 22.1no valid readingsHow it works:
- 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 localdata = list(values)starts empty at every call. - One-pass iterator (module 10):
parse()returns a generator.extend()drains it, sosum(values)adds nothing and the mean is 0.0. Onelist()call gives a container that you can read many times. - Honest hints (module 12): the return hint
tuple[int, float, float] | Nonetells the caller thatNoneis possible. Insideshow(), theis Nonecheck narrows the type, so the unpacking after it is safe. A type checker would flag the unpacking without that check. parse()uses EAFP: it triesfloat()and catches onlyValueError, which coverserror, the empty line andn/a.
P2-03 · Fix the bugs: three checks that lie
Section titled “P2-03 · Fix the bugs: three checks that lie”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 dictionaryEXPECTED_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.0for 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}")products left: 27, books left: ['P022', 'P024']Electronics total 2976.9799999999996 == 2976.98: Falseunits 29533 match: FalseFix the three bugs. Keep the loop that adds the Electronics prices one by one.
products left: 25, books left: []Electronics total 2976.98 matches 2976.98: Trueunits 29533 match: Trueimport csvimport math
EXPECTED_UNITS = 29533 # from the data dictionaryEXPECTED_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 aboveHint 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 csvimport math
EXPECTED_UNITS = 29533 # from the data dictionaryEXPECTED_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.0for 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 booksassert ok and units == EXPECTED_UNITSassert total != EXPECTED_ELECTRONICS # the float sum is not exactproducts left: 25, books left: []Electronics total 2976.98 matches 2976.98: Trueunits 29533 match: TrueHow it works:
- 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. - 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-insum()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. isversus==:isasks whether two names point to the same object. The sum creates a newintobject, soisisFalsealthough the values are equal. Use==for values and keepisforNone.- The units come from a generator expression inside
sum(), which reads the 20,228 lines without building a list (module 10). The checkassert total != EXPECTED_ELECTRONICSdocuments that the float error is real.
P2-04 · Count what each generator stage yields
Section titled “P2-04 · Count what each generator stage yields”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.
before the sink: {}read_rows 8,064with_vibration 8,034above 441chunk 5alerts by sensor: {'S1': 7, 'S2': 10, 'S3': 13, 'S4': 411}above | read_rowsThe last line prints above.__name__ and read_rows.__wrapped__.__name__.
import csvimport functoolsfrom collections import Counterfrom collections.abc import Callable, Iterable, Iteratorfrom itertools import batched
type Reading = tuple[str, str, float] # timestamp, sensor_id, vibrationcounts: 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 csvimport functoolsfrom collections import Counterfrom collections.abc import Callable, Iterable, Iteratorfrom itertools import batched
type Reading = tuple[str, str, float] # timestamp, sensor_id, vibrationcounts: 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
@counteddef read_rows(path: str) -> Iterator[dict[str, str]]: with open(path, encoding="utf-8", newline="") as file: yield from csv.DictReader(file)
@counteddef 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
@counteddef 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"] == 8064assert counts["read_rows"] - counts["with_vibration"] == 30assert by_sensor.total() == counts["above"]before the sink: {}read_rows 8,064with_vibration 8,034above 441chunk 5alerts by sensor: {'S1': 7, 'S2': 10, 'S3': 13, 'S4': 411}above | read_rowsHow it works:
- The three calls in the
pipeline =line only create generators. The counter is still empty, which proves that no row was read (module 10). 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.- 30 rows have a blank vibration cell, as the data dictionary says.
float("")raisesValueError, and the stage skips them. functools.wrapscopies__name__and__doc__and adds__wrapped__, the original function (module 11). The**Pparameter specification keeps the real parameters for a type checker:above(rows, limit="x")would be an error (module 12).- Most alerts come from S4, the sensor with bearing wear from May 12.
P2-05 · A product table from an API with a broken next link
Section titled “P2-05 · A product table from an API with a broken next link”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.
- Write a generator
iter_products(client)that follows thenextlinks and checks every status. Remember each URL that it has fetched. When anextlink points to one of them, raiseRuntimeErrorwith the link in the message. - Describe a product record with
TypedDictclasses. - 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.
- Write a recursive
flatten()that turns nested dicts into dotted keys (price.amount). Print the dotted columns, write all rows tooutput/products_flat.csvand read the file back. - Run
iter_products()againstmake_client(loop=True). Count the products that arrive before the error, and print the error.
30 products, 30 unique idsout 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.countwrote 30 rows, first price 79.99looping API: stopped after 30 products next link loops back to https://api.example.com/v1/products?page=1&per_page=10import jsonfrom collections.abc import Callablefrom 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 csvimport heapqimport jsonfrom collections.abc import Callable, Iterator, Mappingfrom pathlib import Pathfrom 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) == 30assert len(ids) == 30assert len(rows[0]) == 11assert back[0]["price.amount"] == "79.99"30 products, 30 unique idsout 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.countwrote 30 rows, first price 79.99looping API: stopped after 30 products next link loops back to https://api.example.com/v1/products?page=1&per_page=10How it works:
iter_productsis 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).- The set
seenholds every fetched URL. A membership test costs (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. - 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. - The
TypedDictclasses tell the reader and the type checker which keys exist, for examplep["rating"]["count"]. At runtime the records stay plain dicts (module 12). flatten()is recursive: each nested level callsflatten()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.- 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”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 scrapertests/conftest.py # shared fixturestests/test_catalog.py # the tests[tool.pytest]testpaths = ["tests"]pythonpath = ["src"]strict = true
[tool.coverage.report]show_missing = trueexclude_also = ['if __name__ == "__main__":']- In
src/catalog.py, writeparse_catalog(),product_links()andnext_page()with BeautifulSoup and CSS selectors. Make links absolute withurljoin()and the base URLhttps://shop.example.com.mypy --strictmust accept the module. - In
tests/conftest.py, write a session-scoped fixturehtmlthat reads the page once, and a fixturerowsthat parses it. - In
tests/test_catalog.py, check:parse_price()on 4 good inputs, as one parametrized test with readable IDs;ValueErrorwith the messagenot a pricefor bad text; 12 unique products from P001 to P012, the decoded entity inChef's Knife Set, the price of P003 and that only P006 is out of stock; the absolute link of P008; the next-page link, andNoneon a page without one; a CSV round trip in a temporary folder; and thatreport()follows thePRICE_ALERTenvironment variable, from its printed output.
Acceptance criteria:
python src/catalog.pyprints2 of 12 products above 500: ['P003', 'P004'].pytest -qpasses with 0 failures and at least 12 tests, andcoverage reportshows 100% forsrc/catalog.py.- The tests import
catalogwithout anysys.pathchange; thepythonpathsetting 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.
"""Scrape the price table and the links of the shop's catalog page."""
import csvimport osfrom pathlib import Pathfrom typing import TypedDictfrom 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
"""Scrape the price table and the links of the shop's catalog page."""
import csvimport osfrom pathlib import Pathfrom typing import TypedDictfrom 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)2 of 12 products above 500: ['P003', 'P004']"""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.fixturedef rows(html: str) -> list[Row]: return parse_catalog(html)"""Tests for src/catalog.py. Run from the project folder: pytest -q"""
import csvfrom 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']", ]pytest -q --cov=catalog --cov-report=coverage report............. [100%]13 passed in 0.16sName Stmts Miss Cover Missing----------------------------------------------src/catalog.py 44 0 100%----------------------------------------------TOTAL 44 0 100%How it works:
- 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, andh2.product-name a[href]is a link inside its heading (module 16).urljoin()turns/products/p008-chef-s-knife-setinto an absolute URL. next_page()usesselect_one()and narrows itsNoneresult, somypy --strictaccepts the module (module 12).parse_catalog()reads the cells withselect(), which returns a list, and needs no check.pythonpath = ["src"]putssrc/on the import path for the tests, andtestpathsmakes a plainpytestrun collecttests/only (module 14). Thesrc/layout keeps tests and code apart.conftest.pyshares fixtures with every test file in its folder.htmlhasscope="session", so the file is read once per run.rowshas the default function scope, so each test gets a fresh list and cannot spoil another test’s data.tmp_pathis a new empty folder for each test, so the round trip never touchesoutput/.monkeypatch.setenv()setsPRICE_ALERTfor one test only, andcapsyscaptures whatreport()prints.- Coverage counts 44 statements in
src/catalog.py, all run by the tests.exclude_alsoleaves out the smoke check under the main guard, which only thepython src/catalog.pyrun uses. - With
.replace(",", "")removed,test_parse_price[thousands]fails. Therowsfixture 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”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:
- Run it under
cProfilewith its output captured byredirect_stdout. Print the call counts ofchurned_ids,lines_in_monthand the built-insorted, and the name of the function with the most own time (tottime). - Explain in two sentences where the time goes.
- Write
fast_report()with the same output. Use a set and sort the dates once, then count each month withbisect. - 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.
churned_ids: 1 callslines_in_month: 12 calls<built-in method builtins.sorted>: 12 callsmost own time: slow_reportsame output: Truefast is at least 10 times faster: True2568 lines from churned customers2024-01 772024-02 692024-03 892024-04 932024-05 942024-06 1352024-07 1192024-08 1342024-09 1562024-10 1472024-11 2622024-12 330import 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 timesHint 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 cProfileimport csvimport ioimport pstatsimport timeitfrom bisect import bisect_leftfrom 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 checkprofiler = cProfile.Profile()with redirect_stdout(io.StringIO()) as old_output: profiler.runcall(slow_report, sales, customers)functions = pstats.Stats(profiler).get_stats_profile().func_profilesfor 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 fasterwith 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"churned_ids: 1 callslines_in_month: 12 calls<built-in method builtins.sorted>: 12 callsmost own time: slow_reportsame output: Truefast is at least 10 times faster: True2568 lines from churned customers2024-01 772024-02 692024-03 892024-04 932024-05 942024-06 1352024-07 1192024-08 1342024-09 1562024-10 1472024-11 2622024-12 330Interpretation: 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 (). The second waste is sorted with 12 calls on the same 2,568 dates, where one sort is enough.
How it works:
cProfilecounts every call exactly. The times vary from run to run, so the solution prints only the call counts and the name with the largesttottime(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 ofslow_report. On Python 3.11, the top entry would be<listcomp>.redirect_stdoutis a context manager that sendsprint()to aStringIObuffer (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).- A set makes each membership test . One sort costs , and each month then costs two binary searches, (module 17).
"2024-03-99"sorts after every real date of March and before"2024-04-01", so the two bisects bound the whole month.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”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 jsonimport timefrom concurrent.futures import ThreadPoolExecutor, as_completedfrom 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]}")page 1: P021..P030page 2: P011..P020page 3: P001..P010KeyError: '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.
finish order: [3, 2, 1, 4]page 1: 10 products, P001..P010page 2: 10 products, P011..P020page 3: 10 products, P021..P030page 4: HTTP 40430 products from 3 pages# 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 futureHint 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 jsonimport timefrom concurrent.futures import ThreadPoolExecutor, as_completedfrom 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_codeprint("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 == 30assert errors == {4: 404}finish order: [3, 2, 1, 4]page 1: 10 products, P001..P010page 2: 10 products, P011..P020page 3: 10 products, P021..P030page 4: HTTP 40430 products from 3 pagesHow it works:
- Wrong labels (module 15):
as_completed()yields page 3 first, butzip()pairs it with the first item ofpages, 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. - Crash on the missing page (module 16): the 404 body has no
datakey, so the old code fails with aKeyErrorthat hides the real cause.raise_for_status()raiseshttpx.HTTPStatusErrorwith the status code, which the loop records. - 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. - 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.
- The type hints
dict[int, list[str]]anddict[int, int]tell the reader at a glance what each dict maps (module 12).
P2-09 · Rank products by their reviews
Section titled “P2-09 · Rank products by their reviews”Rank the 30 products by the reviews in data/reviews.csv.
- Stream the file with a generator that yields
(product_id, product, rating, review_date). The texts contain line breaks, so use thecsvmodule. - In one pass, group the ratings and the review dates per product with dicts.
- Print the 3 best products by mean rating (ties: more reviews first, then the id) and the 3 worst with
heapq.nsmallest. - 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_righton each product’s sorted dates. - Merge the 30 sorted date lists into one sorted list with
heapq.merge, and print the month with the most reviews, withitertools.groupby.
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 laterbusiest month: 2024-06 with 153 reviewsimport csvimport heapqfrom bisect import bisect_rightfrom collections.abc import Iteratorfrom 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 monthHint 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 csvimport heapqfrom bisect import bisect_rightfrom collections.abc import Iteratorfrom 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 listsper_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) == 24assert sum(per_month.values()) == 30003,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 laterbusiest month: 2024-06 with 153 reviewsHow it works:
- The generator reads one row at a time, and
csv.DictReaderhandles the quoted line breaks inside the texts (module 10). The loop fills three dicts in one pass. The data dictionary gives the same means. setdefaultgroups without anif key in dictcheck (module 13). A hash map turns grouping into one pass (module 17).- A tuple key sorts by several keys at once: negate the numbers that you want in descending order.
heapq.nsmallestkeeps only 3 items and costs . bisect_rightfinds the insertion point after every date equal to the cutoff, in . That is why P005’s review on 2024-06-30 itself counts as “on or before”.bisect_leftwould exclude it.heapq.mergecombines the 30 sorted lists without a full sort: it keeps one item per list in a heap of 30. Theassertchecks that the result is sorted.groupbygroups runs of equal keys, so it needs sorted data. Each month is one run of the merged dates. June 2024 is the busiest month.- 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”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:
"""Rank houses by simple value scores (with type bugs)."""
import csvimport heapqfrom collections.abc import Callable, Iterablefrom 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)mypy --pretty rankers_bad.pyrankers_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: nameFound 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:
price per sqft (low): H1144 Cedar Park 60.3 H0457 Cedar Park 72.5 H1216 Cedar Park 79.0school rating per 100k (high): H2368 Westfield 5.3 H0957 Old Town 5.1 H0476 Maple Grove 4.9largest (high): H2921 Lakeview 5710.0 H0023 Oak Hill 5690.0 H2752 Oak Hill 5180.0Then explain which of the three errors crash at runtime, and what the other one does instead.
# Copy rankers_bad.py to rankers.py.# TODO: fix the three errors that mypy reportsHint 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
"""Rank houses by simple value scores. Check with: mypy --strict rankers.py"""
import csvimport heapqfrom collections.abc import Callable, Iterablefrom 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) == 2910price per sqft (low): H1144 Cedar Park 60.3 H0457 Cedar Park 72.5 H1216 Cedar Park 79.0school rating per 100k (high): H2368 Westfield 5.3 H0957 Old Town 5.1 H0476 Maple Grove 4.9largest (high): H2921 Lakeview 5710.0 H0023 Oak Hill 5690.0 H2752 Oak Hill 5180.0mypy --strict rankers.pyruff check rankers.pyruff format --check rankers.pySuccess: no issues found in 1 source fileAll checks passed!1 file already formattedHow it works:
int | Nonewithout a check (module 12): 90 houses have a blank school rating, soload()storesNone. DividingNoneraisesTypeErrorat runtime. Theis Nonecheck narrows the type, and mypy accepts the division after it.- A value outside the
Literal: Python does not check hints at runtime.top_k()tests onlyorder == "high", so"lowest"silently falls into thensmallestbranch and happens to work. A typo such as"hihg"would also give the lowest houses, without any error. TheLiteralalias lets mypy catch it before the script runs. - Protocol mismatch:
Rankerasks for anameattribute and ascore()method.Largesthadtitle, soshow()would crash withAttributeErrorwhen it printed the heading. Renaming the attribute makes the class match, without inheritance (structural typing). top_k[T]is generic: mypy knows that it returnslist[House]for a list of houses (module 12).heapq.nlargestandnsmallestkeep onlykitems, (module 17).ruff checkfinds style and bug patterns,ruff format --checkreports 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.- 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”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.
- Check the
customer_idof all 20,228 lines ofdata/sales.csvagainst the 5,000 ids ofdata/customers.csv. - Report the 3 sales lines with the highest revenue.
- A gift guide wants to know how many pairs of two different products of
data/products.csvcost at most 50 together. Count them without testing all 435 pairs, and count your steps. - Find the city of the store of every sales line with a function
store_city(store_id)that readsdata/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. - Keep the last 6 valid readings of a sensor stream for a rolling mean.
- Download 30 API pages. Each request waits about 200 ms for the server.
- Run 2,000 bootstrap resamples of a pure-Python statistic on 5,000 customers.
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.00product pairs within 50: 41 (29 pointer steps)store_city calls: 20,228, file reads: 12import 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 commentsHint 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 csvimport heapqfrom 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 totalunknown = 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 sortbudget = 50.0left, right, pairs, steps = 0, len(prices) - 1, 0, 0while 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 -= 1print(f"product pairs within {budget:.0f}: {pairs} ({steps} pointer steps)")
# Job 4: repeated calls with few distinct arguments -> cache, O(1) per hit@cachedef 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 GILbrute = sum( 1 for i in range(len(prices)) for j in range(i + 1, len(prices)) if prices[i] + prices[j] <= budget)assert unknown == 0assert pairs == bruteassert info.misses == 12assert cities.count("New York") == 2541unknown 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.00product pairs within 50: 41 (29 pointer steps)store_city calls: 20,228, file reads: 12| Job | Choice | Cost | Reason |
|---|---|---|---|
| 1 | set of known ids |
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, ...) |
It keeps only 3 items in a heap. A full sort costs to keep 3. | |
| 3 | sort + two pointers | sort, then | Each step moves one pointer, so 30 prices need 29 steps instead of 435 pair tests. |
| 4 | functools.cache |
per repeated call | The function is pure and has 12 distinct inputs, so 12 file reads replace 20,228. |
| 5 | deque(maxlen=6) |
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:
- Each choice follows the operation that runs most often (modules 15 and 17). The data structure decides the speed before any micro-tuning.
heapq.nlargestreturns ties in input order, like a stable sort: both laptop lines have revenue 4,596.00, and the earlier order comes first.- Two pointers on sorted data: when
prices[left] + prices[right]fits the budget, every price between the two pointers fits withprices[left]too, so the loop addsright - leftpairs at once and movesleft. Otherwiseprices[right]is too expensive for every remaining partner, andrightmoves. Theassertchecks the 41 pairs against the brute-force count over all 435 pairs. @cache(anlru_cachewithout 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”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.
- Write down every line it prints, in order, then run it.
- Rewrite the two context managers in the other style:
Stepas a generator functionstep(name)with@contextmanager, andsectionas a classSectionwith__enter__and__exit__. Use them inload(). The script must print the same 14 lines. Capture them withredirect_stdoutto 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 withis printed, and in which order the two context managers exit. - Your rewrite prints the same 14 lines, and
step()suppresses onlyKeyError.
import functoolsfrom collections.abc import Callable, Iteratorfrom contextlib import ExitStack, contextmanager, suppressfrom 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
@contextmanagerdef 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 itHint 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 functoolsfrom collections.abc import Callable, Iteratorfrom contextlib import ExitStack, contextmanager, suppressfrom 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
@contextmanagerdef 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"outer ininner inenter load[csvLOAD 3 row 1 row 2 rows closedcsv]exit load: KeyErrorafter withinner outouter outloadThe rewrite reuses rows() and tag() from above:
import iofrom contextlib import redirect_stdout
@contextmanagerdef 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") == 14assert "exit load: KeyError" in rewritten.getvalue()outer ininner inenter load[csvLOAD 3 row 1 row 2 rows closedcsv]exit load: KeyErrorafter withinner outouter outloadHow it works:
-
@tag("outer")wraps the result of@tag("inner"). A call enters the outer wrapper first, soouter incomes beforeinner in, andinner outcomes beforeouter out(module 11). -
enter_context(Step("load"))printsenter loadand returns"LOAD".enter_context(section("csv"))runs the generator up to itsyield, prints[csvand returnslen("csv"), which is 3. -
The
forloop stops atbreakwhile the generator is paused at its secondyield(module 10).stream.close()raisesGeneratorExitinside it, so itsfinallyprintsrows closed.row 3is never printed. -
int("n/a")raisesValueError.suppresscatches it and skips the rest of its block, sonever printedis never printed. -
KeyErrorleaves thewithblock. TheExitStackexits in reverse order: firstsection, whosefinallyprintscsv], thenStep, which printsexit load: KeyErrorand returnsTrue. A true return value suppresses the exception, so the function goes on withafter with. -
Thanks to
functools.wraps, the global nameload(the outer wrapper) still has the nameload.__wrapped__leads back through both layers to the original function. -
In the rewrite,
step()sees theKeyErrorat itsyield. 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__returnsNone, 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”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:
- 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.envfile. Print only its first 7 characters and its length. - 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 asRetry-Aftersays (or 1, 2, 4 … seconds without the header), and re-raises after the last attempt. Inject a fakesleepthat records the waits, so the script never really waits. - Fetch all 31 ids with one
httpx.AsyncClientandasyncio.gather. Limit the requests in flight with anasyncio.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. - Print the number of products, the units in stock, the sorted waits, the number of requests and the number of busy answers.
key: sk-test... (16 chars)P031: HTTP 404fetched 30 products, P001 to P030units in stock: 3,165waits: [1.0, 2.0, 3.0], requests: 34, busy: 0import asyncioimport jsonimport osfrom collections import Counterfrom 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 reportHint 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 asyncioimport functoolsimport jsonimport osfrom collections import Counterfrom collections.abc import Awaitable, Callablefrom pathlib import Pathfrom 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] = resultprint(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"] == 2assert server["busy"] == 0key: sk-test... (16 chars)P031: HTTP 404fetched 30 products, P001 to P030units in stock: 3,165waits: [1.0, 2.0, 3.0], requests: 34, busy: 0How it works:
- 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.
retry_asynchas three levels: settings, function, call (module 11). Its typed formCallable[P, Awaitable[R]]keeps the real signature ofget_productfor a type checker (module 12).- P013 fails twice with
503, without aRetry-Afterheader, so the waits are 1 and 2 seconds of exponential backoff. P020 gets429withRetry-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. - 31 ids cost 34 requests: 2 extra for P013 and 1 for P020.
404is not transient, so P031 is re-raised at once and becomes a status line. gatherruns 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”. WithSemaphore(5), the fifth request is refused, and the instant fake retries pile up into more than 100 requests.- The semaphore is released before the retry waits. A waiting retry therefore does not block a slot that other products could use.
- This server sends
Retry-Afterin seconds only. The header may also hold an HTTP date (Wed, 21 Oct 2026 07:28:00 GMT), wherefloat(header)raisesValueError. Real code must parse both forms, for example withemail.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”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.
- Write a re-iterable class
TrafficLog(path)whose__iter__is a generator of(date, visits)tuples. A blankvisitscell givesNone(EAFP). - 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 adequeand a running total. Check that both give the same flags. - Group the consecutive spike days with
itertools.groupbyand print each campaign: its first day, its number of spike days and its peak visits. - 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.
5 blank days: 2022-08-11, 2022-08-24, 2023-05-24, 2024-05-29, 2024-10-25start days peak2022-03-14 3 9,1982022-09-06 2 8,9062023-02-20 3 11,2302023-06-12 2 12,6282023-10-02 2 11,2082024-04-08 2 18,3852024-09-16 2 14,446window 7: naive reads 7,588, fast reads 2,168window 28: naive reads 29,764, fast reads 2,126import csvfrom collections import dequefrom collections.abc import Iterable, Iteratorfrom itertools import groupbyfrom 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 28Hint 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 csvfrom collections import dequefrom collections.abc import Iterable, Iteratorfrom itertools import groupbyfrom 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 flagsassert len(campaigns) == 7assert campaigns[0] == "2022-03-14"assert reads["naive"] == 28 * reads["fast"] // 25 blank days: 2022-08-11, 2022-08-24, 2023-05-24, 2024-05-29, 2024-10-25start days peak2022-03-14 3 9,1982022-09-06 2 8,9062023-02-20 3 11,2302023-06-12 2 12,6282023-10-02 2 11,2082024-04-08 2 18,3852024-09-16 2 14,446window 7: naive reads 7,588, fast reads 2,168window 28: naive reads 29,764, fast reads 2,126How it works:
TrafficLogis 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.- 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). FastFlagsimplements the iteration protocol by hand:__iter__returns the object itself, and__next__returns one item or raisesStopIteration(module 10). Its state (the deque and the total) lives in attributes, where a generator keeps it in local variables. UnlikeTrafficLog, aFastFlagsobject is one-pass: a second loop over it gets nothing.- The naive version reads the whole window every day: for days and a window of . Its
list.pop(0)also shifts every item. The fast version updates a running total with one subtraction and one addition: , whatever the window size (modules 15 and 17). With a 28-day window, the naive version reads 14 times more values. groupbyturns the stream of flags into runs. EachTruerun 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.- 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.
Self-assessment rubric
Section titled “Self-assessment rubric”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 window with . |
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
TypedDictand protocols, and fix the errors thatmypy --strictreports. - Write a scraper with CSS selectors and a pytest suite in
tests/, withconftest.pyfixtures, parametrize,tmp_path,monkeypatchandcapsys, 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 loopingnextlink, and handle 404, 429 and 503 correctly. - Spot the gotchas
isversus==, 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.