12. Type hints — Exercises
These exercises practice every idea of the Type hints lesson. They use the course datasets: data/sales.csv, data/customers.csv, data/customers.json, data/houses.csv and the saved API responses in data/api/.
How to work:
- Read the task and the expected output.
- Copy the starter code into a file with the name in its title (for example
ex_w04_lookup.py) and replace each to-do comment with your code. - Run it with
python file.py. For the exercises that use mypy, also runmypy file.pyormypy --strict file.py, as the task says. - Stuck? Open one hint at a time. Open the solution only after a real attempt.
Some exercises import the lesson files customer_types.py, product_types.py and models.py. Save them from the lesson into the same folder first. Put the lesson’s pyproject.toml (with pretty = true) there too, so your mypy output looks like the output on this page.
Warm-up
Section titled “Warm-up”M12-W01 · Annotate an order total
Section titled “M12-W01 · Annotate an order total”Write order_total(quantities, unit_prices, discount=0.0) with full hints: two lists (int quantities, float prices), a float discount and a float return value. It returns the discounted total, rounded to 2 decimals. Call it for an order of 3 headphones (249.00), 1 pair of earbuds (79.99) and 2 pairs of running socks (14.99) with a 10% discount. Then print each hint from order_total.__annotations__.
Total: 771.27quantities: list[int]unit_prices: list[float]discount: <class 'float'>return: <class 'float'>def order_total(quantities, unit_prices, discount=0.0): # TODO: add hints to the parameters and the return value # TODO: return the discounted total, rounded to 2 decimals ...
# TODO: print the total for quantities [3, 1, 2] and prices [249.0, 79.99, 14.99]# TODO: print each name and hint from order_total.__annotations__Hint 1
The signature starts def order_total(quantities: list[int], unit_prices: list[float], .... Break it over several lines if it gets longer than 88 characters.
Hint 2
zip(quantities, unit_prices, strict=True) pairs each quantity with its price. strict=True raises an error if the lists have different lengths.
Solution
def order_total( quantities: list[int], unit_prices: list[float], discount: float = 0.0) -> float: """Return the discounted total of an order, rounded to cents.""" gross = sum(q * p for q, p in zip(quantities, unit_prices, strict=True)) return round(gross * (1 - discount), 2)
total = order_total([3, 1, 2], [249.0, 79.99, 14.99], discount=0.1)print("Total:", total)for name, hint in order_total.__annotations__.items(): print(f"{name}: {hint}")
assert total == 771.27assert order_total([1], [10.0]) == 10.0assert order_total.__annotations__["return"] is floatTotal: 771.27quantities: list[int]unit_prices: list[float]discount: <class 'float'>return: <class 'float'>How it works:
- Each parameter gets
name: type, and the return type follows->. - The gross total is 3 × 249.00 + 79.99 + 2 × 14.99 = 856.97. The 10% discount gives 771.273, which rounds to 771.27.
__annotations__stores the hints as objects. A plain class prints as<class 'float'>; a generic such aslist[int]prints as written.
Alternative: accept Sequence[int] and Sequence[float] from collections.abc instead of lists, so callers can also pass tuples. The lesson explains why read-only inputs should use Sequence.
M12-W02 · Predict the output: hints are not checks
Section titled “M12-W02 · Predict the output: hints are not checks”Predict the output: what does each line print? The function promises to take and return an int.
Acceptance criteria:
- Write your prediction for every line before you run the code.
- Run the code. Your prediction matches the Output in the solution, line by line.
- You can say which calls mypy would reject.
def double_units(units: int) -> int: return units * 2
print(double_units(21))print(double_units("21"))print(double_units(2.5))print(double_units([1, 2]))# TODO: write your prediction for each line before you run itHint 1
Python ignores the hints when it runs the code. Ask what * does with each type.
Hint 2
* with a string or a list repeats it. A float times an int is a float.
Solution
def double_units(units: int) -> int: return units * 2
print(double_units(21))print(double_units("21"))print(double_units(2.5))print(double_units([1, 2]))
assert double_units("21") == "2121" # the hint did not stop the callassert double_units([1, 2]) == [1, 2, 1, 2]4221215.0[1, 2, 1, 2]How it works:
21 * 2is42, as intended."21" * 2repeats the string:"2121". No error, and the result is wrong. This is the typical bug when a number arrives as text from a file.2.5 * 2is5.0, afloatalthough the hint promises anint.[1, 2] * 2repeats the list.- mypy rejects the second, third and fourth calls: each argument is not an
int. Python accepts all four.
M12-W03 · Annotate nested sales data
Section titled “M12-W03 · Annotate nested sales data”The units sold per order line for three stores are stored as a dict of lists. Annotate the variable, then write store_totals (returns the total units per store) and best_store (returns the store id and its total as a tuple), both with full hints.
Totals: {'S01': 7, 'S02': 9, 'S03': 4}Best: ('S02', 9)units_by_store = {"S01": [1, 2, 4], "S02": [3, 3, 1, 2], "S03": [4]} # TODO: hint
def store_totals(units_by_store): # TODO: hints ...
def best_store(totals): # TODO: hints; return (store_id, total) ...
# TODO: print the totals and the best storeHint 1
The data is dict[str, list[int]]. The totals are dict[str, int]. A pair of a str and an int is tuple[str, int].
Hint 2
max(totals.items(), key=lambda item: item[1]) returns the (key, value) pair with the largest value.
Solution
units_by_store: dict[str, list[int]] = { "S01": [1, 2, 4], "S02": [3, 3, 1, 2], "S03": [4],}
def store_totals(units_by_store: dict[str, list[int]]) -> dict[str, int]: return {store: sum(units) for store, units in units_by_store.items()}
def best_store(totals: dict[str, int]) -> tuple[str, int]: return max(totals.items(), key=lambda item: item[1])
totals = store_totals(units_by_store)print("Totals:", totals)print("Best:", best_store(totals))
assert totals == {"S01": 7, "S02": 9, "S03": 4}assert best_store(totals) == ("S02", 9)Totals: {'S01': 7, 'S02': 9, 'S03': 4}Best: ('S02', 9)How it works:
dict[str, list[int]]says: store ids are strings, and each value is a list of whole-number quantities.- The comprehension builds
dict[str, int], one total per store. maxwith a key function compares the pairs by their second item.dict.items()yieldstuple[str, int]pairs, so the return hint matches.
Alternative: max(totals, key=totals.__getitem__) returns only the store id; you then look up the total yourself.
M12-W04 · Fix the bug: a lookup that can miss
Section titled “M12-W04 · Fix the bug: a lookup that can miss”Fix the bug: this price lookup claims to always return a float, but dict.get() returns None for an unknown id. mypy reports it:
"""Look up product prices by id (with a type bug)."""
PRICES: dict[str, float] = {"P001": 79.99, "P002": 249.0, "P006": 349.0}
def price_of(product_id: str) -> float: return PRICES.get(product_id)
print(price_of("P001"), price_of("P999"))# TODO: make the return hint honest and handle a missing id at the callermypy ex_w04_lookup.pyex_w04_lookup.py:7: error: Incompatible return value type (got "float | None", expected "float")[return-value] return PRICES.get(product_id) ^~~~~~~~~~~~~~~~~~~~~~Found 1 error in 1 file (checked 1 source file)Make the hint tell the truth. Then print each price with 2 decimals, or unknown for a missing id, for P001 and P999. mypy --strict must pass.
P001: 79.99P999: unknownHint 1
The function can return a float or None. Which hint says exactly that?
Hint 2
At the caller, store the result in a variable and test if price is None: before you format it with :.2f.
Solution
"""Look up product prices by id; a missing id gives None."""
PRICES: dict[str, float] = {"P001": 79.99, "P002": 249.0, "P006": 349.0}
def price_of(product_id: str) -> float | None: return PRICES.get(product_id)
for product_id in ("P001", "P999"): price = price_of(product_id) if price is None: print(f"{product_id}: unknown") else: print(f"{product_id}: {price:.2f}")
assert price_of("P002") == 249.0assert price_of("P999") is NoneP001: 79.99P999: unknownmypy --strict ex_w04_lookup_fixed.pySuccess: no issues found in 1 source fileHow it works:
PRICES.get(product_id)has the typefloat | None, so the honest return hint isfloat | None.- The caller now must handle
None. Inside theelsebranch, mypy has narrowedpricetofloat, so:.2fis safe. - Without the
is Nonecheck,f"{price:.2f}"would crash at runtime forP999withTypeError: unsupported format string passed to NoneType.__format__.
Alternative: if a default makes sense, keep -> float and return one: return PRICES.get(product_id, 0.0). Then the type is float. But a price of 0.0 hides the fact that the product is unknown, so the None version is safer here.
M12-W05 · A Literal for the plan
Section titled “M12-W05 · A Literal for the plan”The subscription plans in data/customers.csv are basic, standard and premium. Define an alias Plan with Literal and a fee table dict[Plan, float] (basic 29.99, standard 54.99, premium 89.99). Write annual_fee(plan: Plan) -> float and a runtime check parse_plan(text: str) -> Plan, which strips and lowercases the text and raises ValueError for an unknown plan. Read the allowed values from the alias with get_args.
standard 659.88premium 1079.88ValueError: unknown plan 'gold'; expected one of ('basic', 'standard', 'premium')from typing import Literal, cast, get_args
type Plan = ... # TODO: the three plan namesMONTHLY_FEE = {} # TODO: hint and values
def annual_fee(plan): # TODO: hints; 12 monthly fees, rounded to 2 decimals ...
def parse_plan(text): # TODO: hints; raise ValueError for unknown plans ...
for raw in (" Standard", "premium", "gold"): # TODO: parse, print the plan and its annual fee, catch ValueError ...Hint 1
type Plan = Literal["basic", "standard", "premium"]. The values of a type alias are in Plan.__value__, so get_args(Plan.__value__) gives the tuple of names.
Hint 2
After you check if value not in allowed: raise ..., the checker still sees a str. Return cast(Plan, value): the check makes the cast honest.
Solution
from typing import Literal, cast, get_args
type Plan = Literal["basic", "standard", "premium"]MONTHLY_FEE: dict[Plan, float] = {"basic": 29.99, "standard": 54.99, "premium": 89.99}
def annual_fee(plan: Plan) -> float: return round(12 * MONTHLY_FEE[plan], 2)
def parse_plan(text: str) -> Plan: value = text.strip().lower() allowed = get_args(Plan.__value__) if value not in allowed: raise ValueError(f"unknown plan {value!r}; expected one of {allowed}") return cast(Plan, value)
for raw in (" Standard", "premium", "gold"): try: plan = parse_plan(raw) print(plan, annual_fee(plan)) except ValueError as exc: print("ValueError:", exc)
assert annual_fee("basic") == 359.88assert parse_plan("PREMIUM ") == "premium"standard 659.88premium 1079.88ValueError: unknown plan 'gold'; expected one of ('basic', 'standard', 'premium')How it works:
- The alias lists the three valid plans once. The fee table and both functions reuse it.
annual_fee("gold")would fail the type check. Text from a file is only astr, soparse_planchecks it at runtime.get_args(Plan.__value__)returns('basic', 'standard', 'premium'), so the runtime check and the type can never disagree.
Alternative: an Enum (module 21) gives the same safety plus a real runtime type: Plan("gold") raises ValueError by itself.
M12-W06 · Interpret: read a mypy report line
Section titled “M12-W06 · Interpret: read a mypy report line”Interpret a result: below is one line of a mypy report from the lesson. Name its five parts (file, line, severity, message, error code) and say what the bug is. Then write parse_report_line(line: str) -> tuple[str, int, str, str, str] that splits such a line into these five parts, so a CI script could count errors by code.
file: clean_readings.pyline: 27severity: errormsg: Argument 1 to "summarize" has incompatible type "list[float | None]"; expected "list[float]"code: arg-typereport = ( 'clean_readings.py:27: error: Argument 1 to "summarize" has incompatible type ' '"list[float | None]"; expected "list[float]" [arg-type]')
def parse_report_line(line): # TODO: hints # TODO: split off the file, line and severity; then the code in [...] ...
# TODO: print the five parts with their labelsHint 1
line.split(": ", 2) cuts at the first two ": " separators. But the file name and line number are joined by ":" without a space.
Hint 2
Split in two steps: location, severity, rest = line.split(": ", 2), then path, number = location.split(":"). The code is between the last [ and the final ]: rest.rsplit(" [", 1).
Solution
report = ( 'clean_readings.py:27: error: Argument 1 to "summarize" has incompatible type ' '"list[float | None]"; expected "list[float]" [arg-type]')
def parse_report_line(line: str) -> tuple[str, int, str, str, str]: """Split one mypy line into file, line number, severity, message and code.""" location, severity, rest = line.split(": ", 2) path, number = location.split(":") message, code = rest.rsplit(" [", 1) return path, int(number), severity, message, code.rstrip("]")
labels = ("file", "line", "severity", "msg", "code")parts = parse_report_line(report)for label, part in zip(labels, parts, strict=True): print(f"{label}: {part}")
assert parts[1] == 27assert parts[4] == "arg-type"file: clean_readings.pyline: 27severity: errormsg: Argument 1 to "summarize" has incompatible type "list[float | None]"; expected "list[float]"code: arg-typeHow it works:
- Interpretation: at line 27 of
clean_readings.py, alist[float | None]is passed tosummarize, which accepts onlylist[float]. The list still contains theNonevalues of the broken lines. The codearg-typemeans “an argument has the wrong type”. split(": ", 2)makes at most two cuts, so colons inside the message stay inrest.- mypy puts two spaces before the code in brackets.
rsplit(" [", 1)cuts only at the last occurrence. - The line number becomes an
int, which matches the return hint.
Alternative: a regular expression with named groups, re.match(r"(?P<path>[^:]+):(?P<line>\d+): (?P<sev>\w+): (?P<msg>.*) \[(?P<code>[\w-]+)\]$", line), does the same in one pattern (module 09). mypy can also write a machine-readable report with --output json.
M12-W07 · Pass a rule as a Callable
Section titled “M12-W07 · Pass a rule as a Callable”Write flag_readings(readings, is_bad) with full hints. It returns the positions of the readings for which the function is_bad returns True. Use it twice on the readings below: once with a named function out_of_range (outside 19.0 to 23.0 °C) and once with a lambda for “colder than 20.0”.
Out of range: [2, 5]Below 20.0: [1, 2]from collections.abc import Callable
readings = [21.0, 19.3, 18.7, 21.4, 22.9, 23.4]
def flag_readings(readings, is_bad): # TODO: hints ...
def out_of_range(celsius): # TODO: hints ...
# TODO: print both lists of positionsHint 1
is_bad takes one float and returns a bool: Callable[[float], bool].
Hint 2
[i for i, value in enumerate(readings) if is_bad(value)] collects the positions.
Solution
from collections.abc import Callable
readings = [21.0, 19.3, 18.7, 21.4, 22.9, 23.4]
def flag_readings(readings: list[float], is_bad: Callable[[float], bool]) -> list[int]: return [i for i, value in enumerate(readings) if is_bad(value)]
def out_of_range(celsius: float) -> bool: return not 19.0 <= celsius <= 23.0
print("Out of range:", flag_readings(readings, out_of_range))print("Below 20.0:", flag_readings(readings, lambda c: c < 20.0))
assert flag_readings(readings, out_of_range) == [2, 5]assert flag_readings([], out_of_range) == []Out of range: [2, 5]Below 20.0: [1, 2]How it works:
Callable[[float], bool]accepts any function with one float parameter and a bool result: a named function or a lambda.enumeratepairs each reading with its position, and the condition keeps the positions where the rule saysTrue.- The checker infers the lambda’s parameter type from the hint, so
cis afloatinside it.
Alternative: return the readings instead of positions with [v for v in readings if is_bad(v)], or use filter(is_bad, readings).
M12-W08 · Predict the output: what mypy reveals
Section titled “M12-W08 · Predict the output: what mypy reveals”Predict the output: for each reveal_type() line, write down the type that mypy infers. Then run mypy ex_w08_reveal.py.
Acceptance criteria:
- Write your five predictions before you run mypy.
- Your predictions match the five
Revealed typenotes in the solution. - You can explain the third one: why is there a
None?
"""Predict what mypy reveals for each expression."""
from typing import reveal_type
prices = {"P001": 79.99, "P002": 249.0}ids = sorted(prices)
reveal_type(prices)reveal_type(ids)reveal_type(prices.get("P003"))reveal_type(len(ids) / 2)reveal_type([price > 100 for price in prices.values()])Hint 1
mypy infers the type of a dict literal from its keys and values. sorted() of a dict sorts its keys.
Hint 2
dict.get() without a default can miss. And / always returns a float.
Solution
mypy ex_w08_reveal.pyex_w08_reveal.py:8: note: Revealed type is "dict[str, float]"ex_w08_reveal.py:9: note: Revealed type is "list[str]"ex_w08_reveal.py:10: note: Revealed type is "float | None"ex_w08_reveal.py:11: note: Revealed type is "float"ex_w08_reveal.py:12: note: Revealed type is "list[bool]"Success: no issues found in 1 source fileThe same facts, checked at runtime:
prices = {"P001": 79.99, "P002": 249.0}ids = sorted(prices)print(type(prices.get("P003")).__name__, type(len(ids) / 2).__name__, ids)
assert prices.get("P003") is Noneassert isinstance(len(ids) / 2, float)NoneType float ['P001', 'P002']How it works:
- The dict literal has
strkeys andfloatvalues, so it is adict[str, float].sorted()returns a list of its keys:list[str]. prices.get("P003")returnsNonewhen the key is missing. mypy does not know which keys exist, so the type isfloat | None./gives afloateven for two ints. A comparison gives abool, so the comprehension is alist[bool].- Notes are not errors, so the run ends with
Success.
M12-C01 · TypedDicts for API products
Section titled “M12-C01 · TypedDicts for API products”data/api/products_page_2.json holds 10 products. Each item looks like {"id": "P011", "name": ..., "category": ..., "price": {"amount": ..., "currency": "USD"}, "in_stock": ..., "stock": ..., "rating": {"average": ..., "count": ...}, ...}. Write TypedDicts Price, Rating and Product (with the keys you need: id, name, category, price, in_stock, rating) and Page (page, data). Load the file with cast. Print the page number, the number of products, the best-rated product and the out-of-stock ids.
Page 2: 10 productsBest rated: Adjustable Dumbbells (4.3 from 53 reviews)Out of stock: ['P019']import jsonfrom typing import TypedDict, cast
# TODO: class Price, class Rating, class Product, class Page
def load_page(path: str): # TODO: return type ...
page = load_page("data/api/products_page_2.json")# TODO: print the three linesHint 1
Nested JSON objects become nested TypedDicts: price: Price and rating: Rating inside Product. A TypedDict may describe fewer keys than the JSON has; the extra keys are still in the dict at runtime.
Hint 2
max(page["data"], key=lambda p: p["rating"]["average"]) finds the best-rated product. If two products tie, max keeps the first.
Solution
import jsonfrom typing import TypedDict, cast
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 rating: Rating
class Page(TypedDict): page: int data: list[Product]
def load_page(path: str) -> Page: with open(path, encoding="utf-8") as f: return cast(Page, json.load(f))
page = load_page("data/api/products_page_2.json")products = page["data"]best = max(products, key=lambda p: p["rating"]["average"])print(f"Page {page['page']}: {len(products)} products")print( f"Best rated: {best['name']} " f"({best['rating']['average']} from {best['rating']['count']} reviews)")print("Out of stock:", [p["id"] for p in products if not p["in_stock"]])
assert len(products) == 10assert all(p["price"]["currency"] == "USD" for p in products)Page 2: 10 productsBest rated: Adjustable Dumbbells (4.3 from 53 reviews)Out of stock: ['P019']How it works:
- One TypedDict per JSON object. Nesting in the JSON becomes nesting in the types.
cast(Page, json.load(f))turns theAnyfromjson.loadinto a typed value. From here on, the editor completes keys and the checker rejects typos.- The key function reads two levels deep. The checker knows that
p["rating"]["average"]is afloat, somaxcan compare it.
Alternative: describe every key of the API (as product_types.py in the lesson does) and import the types instead of writing them again. Shared types in one module keep all scripts in sync.
M12-C02 · Fix the bugs: hourly weather records
Section titled “M12-C02 · Fix the bugs: hourly weather records”Fix the bugs: this script summarizes the hourly forecast in data/api/weather_forecast.json. Each hourly record has time, temperature_c, precipitation_probability (0–100) and wind ({"speed_kmh": ..., "direction_deg": ...}). mypy finds the bugs before you run it:
"""Summarize the hourly forecast in data/api/weather_forecast.json (2 bugs)."""
import jsonfrom pathlib import Pathfrom typing import TypedDict, cast
class Wind(TypedDict): speed_kmh: float direction_deg: int
class Hour(TypedDict): time: str temperature_c: float precipitation_probability: int wind: Wind
class Forecast(TypedDict): hourly: list[Hour]
def load_forecast(path: Path) -> Forecast: with path.open(encoding="utf-8") as f: return cast(Forecast, json.load(f))
def rainy_hours(hours: list[Hour], threshold: int = 50) -> list[str]: return [h["time"] for h in hours if h["precipitation_chance"] >= threshold]
def max_wind(hours: list[Hour]) -> float: return max(h["wind"] for h in hours)
hours = load_forecast(Path("data/api/weather_forecast.json"))["hourly"]rainy = rainy_hours(hours)print(len(rainy), "rainy hours, from", rainy[0], "to", rainy[-1])print("Max wind:", max_wind(hours), "km/h")# TODO: fix the key name and the max_wind bug until mypy --strict passesmypy ex_c02_weather.pyex_c02_weather.py:30: error: TypedDict "Hour" has no key "precipitation_chance" [typeddict-item] return [h["time"] for h in hours if h["precipitation_chance"] >= threshold] ^~~~~~~~~~~~~~~~~~~~~~ex_c02_weather.py:34: error: Value of type variable "SupportsRichComparisonT" of "max" cannot be"Wind" [type-var] return max(h["wind"] for h in hours) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ex_c02_weather.py:34: error: Incompatible return value type (got "Wind", expected "float")[return-value] return max(h["wind"] for h in hours) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~Found 3 errors in 1 file (checked 1 source file)Interpret the three errors, fix both bugs and make mypy --strict pass. Add two assert checks at the end.
10 rainy hours, from 2024-05-02T00:00 to 2024-05-02T09:00Max wind: 27.3 km/hHint 1
The first error is a misspelled key. Compare it with the keys of Hour.
Hint 2
h["wind"] is a whole Wind dict. Dicts cannot be compared with <, so max cannot rank them (that is what “type variable … cannot be Wind” means). Which number inside Wind do you want?
Solution
"""Summarize the hourly forecast in data/api/weather_forecast.json."""
import jsonfrom pathlib import Pathfrom typing import TypedDict, cast
class Wind(TypedDict): speed_kmh: float direction_deg: int
class Hour(TypedDict): time: str temperature_c: float precipitation_probability: int wind: Wind
class Forecast(TypedDict): hourly: list[Hour]
def load_forecast(path: Path) -> Forecast: with path.open(encoding="utf-8") as f: return cast(Forecast, json.load(f))
def rainy_hours(hours: list[Hour], threshold: int = 50) -> list[str]: return [h["time"] for h in hours if h["precipitation_probability"] >= threshold]
def max_wind(hours: list[Hour]) -> float: return max(h["wind"]["speed_kmh"] for h in hours)
hours = load_forecast(Path("data/api/weather_forecast.json"))["hourly"]rainy = rainy_hours(hours)print(len(rainy), "rainy hours, from", rainy[0], "to", rainy[-1])print("Max wind:", max_wind(hours), "km/h")
assert len(rainy) == 10assert all(h["temperature_c"] > -50 for h in hours)10 rainy hours, from 2024-05-02T00:00 to 2024-05-02T09:00Max wind: 27.3 km/hmypy --strict ex_c02_weather_fixed.pySuccess: no issues found in 1 source fileHow it works:
- Error 1 names the missing key and the TypedDict. The JSON key is
precipitation_probability. At runtime, this bug is aKeyErroron the first hour. - Errors 2 and 3 come from one bug.
maxneeds values it can compare; aWinddict is not one. And even if it worked, the result would be aWind, not the promisedfloat. Reading["speed_kmh"]fixes both. - One wrong line often produces several messages. Fix the first error on a line, then run mypy again.
Forecastdescribes onlyhourly, although the JSON also haslocation,dailyand more. A TypedDict needs only the keys your code uses.
M12-C03 · Average with missing values
Section titled “M12-C03 · Average with missing values”Session minutes can be missing (None). Write mean_or_none(values: list[float | None]) -> float | None: it returns the mean of the known values, rounded to 1 decimal, or None when no value is known. Then write describe(value: float | None) -> str that returns "12.3 min" or "no data". Print a line for each of the three customers below.
C03991: 6.4 minC00002: 15.1 minC04995: no datasessions = { "C03991": [6.4, None, 6.4], "C00002": [15.2, 14.9, None, 15.2], "C04995": [None, None],}
def mean_or_none(values): # TODO: hints ...
def describe(value): # TODO: hints ...
# TODO: print one line per customerHint 1
Narrow the list first: known = [v for v in values if v is not None] has the type list[float].
Hint 2
An empty list is falsy: if not known: return None. In describe, test value is None before you format with :.1f.
Solution
sessions: dict[str, list[float | None]] = { "C03991": [6.4, None, 6.4], "C00002": [15.2, 14.9, None, 15.2], "C04995": [None, None],}
def mean_or_none(values: list[float | None]) -> float | None: known = [v for v in values if v is not None] if not known: return None return round(sum(known) / len(known), 1)
def describe(value: float | None) -> str: return "no data" if value is None else f"{value:.1f} min"
for customer_id, values in sessions.items(): print(f"{customer_id}: {describe(mean_or_none(values))}")
assert mean_or_none([None]) is Noneassert mean_or_none([0.0, None]) == 0.0C03991: 6.4 minC00002: 15.1 minC04995: no dataHow it works:
- The comprehension with
is not Noneremoves the gaps and narrows the type tolist[float], sosumis safe. - “No known value” is a real outcome, so the return hint says
float | None. Returning0.0would claim a session time of zero. describehandles both cases. Inside the conditional expression, the checker knows thatvalueis afloatin theelsepart.- The second assert checks that a real
0.0is kept: a test withif vinstead ofis not Nonewould drop it.
Alternative: statistics.fmean(known) computes the mean of floats directly and fast.
M12-C04 · Refactor: make an untyped helper pass strict mode
Section titled “M12-C04 · Refactor: make an untyped helper pass strict mode”Refactor: this script computes the revenue per category in data/sales.csv. It runs, and mypy says Success, but mypy --strict reports 5 errors. (grep error keeps only the first line of each message; mypy wraps the long ones.) Add hints until mypy --strict passes, without changing the output.
"""Revenue per category from data/sales.csv (no hints yet)."""
import csv
def revenue_by_category(rows): totals = {} for row in rows: category = row["category"] totals[category] = totals.get(category, 0.0) + float(row["revenue"]) return totals
def top_categories(totals, n=3): return sorted(totals, key=totals.get, reverse=True)[:n]
with open("data/sales.csv", encoding="utf-8", newline="") as f: totals = revenue_by_category(csv.DictReader(f))for category in top_categories(totals): print(f"{category:<12} {totals[category]:>14,.2f}")# TODO: add hints until mypy --strict passes, without changing the outputmypy --strict ex_c04_untyped.py | grep errorex_c04_untyped.py:6: error: Function is missing a type annotation [no-untyped-def]ex_c04_untyped.py:7: error: Need type annotation for "totals" (hint:ex_c04_untyped.py:14: error: Function is missing a type annotation [no-untyped-def]ex_c04_untyped.py:19: error: Call to untyped function "revenue_by_category" in typed contextex_c04_untyped.py:20: error: Call to untyped function "top_categories" in typed contextFound 5 errors in 1 file (checked 1 source file)Electronics 1,808,108.17Home 672,294.61Sports 544,108.55Hint 1
csv.DictReader yields one dict of strings per row. A parameter that is only looped over can be Iterable[dict[str, str]]. The empty totals needs a hint: dict[str, float].
Hint 2
Once totals is typed, mypy also rejects key=totals.get: get can return None, and None cannot be compared. Use a key that always returns a float.
Solution
"""Revenue per category from data/sales.csv, with full hints."""
import csvfrom collections.abc import Iterable
def revenue_by_category(rows: Iterable[dict[str, str]]) -> dict[str, float]: totals: dict[str, float] = {} for row in rows: category = row["category"] totals[category] = totals.get(category, 0.0) + float(row["revenue"]) return totals
def top_categories(totals: dict[str, float], n: int = 3) -> list[str]: return sorted(totals, key=lambda category: totals[category], reverse=True)[:n]
with open("data/sales.csv", encoding="utf-8", newline="") as f: totals = revenue_by_category(csv.DictReader(f))for category in top_categories(totals): print(f"{category:<12} {totals[category]:>14,.2f}")
assert top_categories({"A": 1.0, "B": 3.0, "C": 2.0}, n=2) == ["B", "C"]assert round(sum(totals.values()), 2) == 3596523.83Electronics 1,808,108.17Home 672,294.61Sports 544,108.55mypy --strict ex_c04_typed.pySuccess: no issues found in 1 source fileHow it works:
- Annotating both functions fixes four errors: the two missing annotations and the two “untyped call” errors at the bottom.
totals: dict[str, float] = {}fixes the fifth. An empty dict alone tells mypy nothing about its keys and values.key=totals.getwas fine for Python but not for the checker:getreturnsfloat | None, andsortedcannot compareNone. The lambdatotals[category]always returns afloat. mypy found this only after the dict had a type.Iterable[dict[str, str]]accepts theDictReaderand also a plain list of dicts in a test. The asserts check the helper on small data and the grand total against the dataset (3,596,523.83).
Alternative: collections.Counter or defaultdict(float) (module 09) shortens the loop: totals: defaultdict[str, float] = defaultdict(float).
M12-C05 · Generic last and top_n
Section titled “M12-C05 · Generic last and top_n”Write two generic functions with the PEP 695 syntax: last[T](items: Sequence[T]) -> T returns the last item, and top_n[T](items: Iterable[T], n: int, key: Callable[[T], float]) -> list[T] returns the n items with the largest key, largest first. Use them on the readings and on (product_id, price) pairs below.
Last reading: 22.1Last product: ('P006', 349.0)Top 2 readings: [22.1, 21.9]Top 2 products by price: [('P006', 349.0), ('P002', 249.0)]from collections.abc import Callable, Iterable, Sequence
readings = [21.0, 21.9, 21.4, 21.7, 22.1]products = [("P001", 79.99), ("P002", 249.0), ("P014", 14.99), ("P006", 349.0)]
# TODO: def last[T](...)# TODO: def top_n[T](...)
# TODO: print the four linesHint 1
sorted(items, key=key, reverse=True)[:n] already does the work of top_n. The hint is what makes it generic.
Hint 2
For the readings, the key is the value itself: key=lambda r: r. For the pairs, key=lambda p: p[1].
Solution
from collections.abc import Callable, Iterable, Sequence
readings = [21.0, 21.9, 21.4, 21.7, 22.1]products = [("P001", 79.99), ("P002", 249.0), ("P014", 14.99), ("P006", 349.0)]
def last[T](items: Sequence[T]) -> T: return items[-1]
def top_n[T](items: Iterable[T], n: int, key: Callable[[T], float]) -> list[T]: return sorted(items, key=key, reverse=True)[:n]
print("Last reading:", last(readings))print("Last product:", last(products))print("Top 2 readings:", top_n(readings, 2, key=lambda r: r))print("Top 2 products by price:", top_n(products, 2, key=lambda p: p[1]))
assert last("abc") == "c"assert top_n([], 3, key=float) == []Last reading: 22.1Last product: ('P006', 349.0)Top 2 readings: [22.1, 21.9]Top 2 products by price: [('P006', 349.0), ('P002', 249.0)]How it works:
Tlinks the input to the output. Forlast(products),Tistuple[str, float], so the checker knows thatlast(products)[1]is a float.- In
top_n,Tappears three times: in the items, in the key function’s parameter and in the result. The checker infersTfrom the items and then checks the lambda againstCallable[[T], float]. lastneeds indexing, so it takes aSequence.top_nonly loops, so it takes anyIterable, even a generator.
Alternative: heapq.nlargest(n, items, key=key) from the standard library does the same as top_n and is faster for large inputs; its typeshed hints are generic in the same way.
M12-C06 · Type aliases for a feature matrix
Section titled “M12-C06 · Type aliases for a feature matrix”Define the aliases type Row = list[float] and type Matrix = list[Row]. Write standardize(X: Matrix) -> Matrix: it replaces each value with its column z-score, (value − column mean) / column population standard deviation, rounded to 2 decimals. Apply it to four houses from data/houses.csv with the columns sqft and bedrooms.
[1.54, 1.51][-0.38, -0.9][-1.21, -0.9][0.05, 0.3]from statistics import fmean, pstdev
# TODO: type Row and type Matrix
houses = [[2420.0, 4.0], [1610.0, 2.0], [1260.0, 2.0], [1790.0, 3.0]] # TODO: hint
def standardize(X): # TODO: hints ...
# TODO: print each standardized rowHint 1
zip(*X) turns the rows into columns. Compute the mean and standard deviation of each column first.
Hint 2
Build the result row by row: [round((value - m) / s, 2) for value, m, s in zip(row, means, stds)].
Solution
from statistics import fmean, pstdev
type Row = list[float]type Matrix = list[Row]
houses: Matrix = [[2420.0, 4.0], [1610.0, 2.0], [1260.0, 2.0], [1790.0, 3.0]]
def standardize(X: Matrix) -> Matrix: """Return the column z-scores of X, rounded to 2 decimals.""" columns = list(zip(*X, strict=True)) means = [fmean(column) for column in columns] stds = [pstdev(column) for column in columns] return [ [round((v - m) / s, 2) for v, m, s in zip(row, means, stds, strict=True)] for row in X ]
scaled = standardize(houses)for row in scaled: print(row)
assert len(scaled) == len(houses)assert abs(sum(row[0] for row in scaled)) < 0.05 # z-scores sum to about 0[1.54, 1.51][-0.38, -0.9][-1.21, -0.9][0.05, 0.3]How it works:
- The aliases name the shapes of the data, so
standardize(X: Matrix) -> Matrixreads as “a matrix in, a matrix out”. zip(*X)transposes the rows into columns. Each column gets its mean and population standard deviation.- Each value becomes its distance from the column mean in standard deviations. This is what scikit-learn’s
StandardScalerdoes (module 33). - To the checker,
Matrixis exactlylist[list[float]]. An alias adds a name, not a new type.
Alternative: in real work, store the matrix as a NumPy array (module 23) and write (X - X.mean(axis=0)) / X.std(axis=0). The hint is then numpy.typing.NDArray[np.float64].
M12-C07 · Choose and justify: list[float] or Sequence[float]
Section titled “M12-C07 · Choose and justify: list[float] or Sequence[float]”Choose a method and justify it: this read-only function is hinted with list[float]. Both calls run, but mypy rejects both. (The command hides one long note line with a link to the mypy docs.)
"""Which hint should a read-only price function accept?"""
def mean_price(prices: list[float]) -> float: return sum(prices) / len(prices)
whole_dollar_prices = [79, 249, 15] # mypy infers list[int]print(mean_price(whole_dollar_prices))print(mean_price((79.99, 249.0)))# TODO: choose a better parameter hint and justify itmypy ex_c07_invariance.py | grep -v "https://"ex_c07_invariance.py:9: error: Argument 1 to "mean_price" has incompatible type "list[int]";expected "list[float]" [arg-type] print(mean_price(whole_dollar_prices)) ^~~~~~~~~~~~~~~~~~~ex_c07_invariance.py:9: note: Consider using "Sequence" instead, which is covariantex_c07_invariance.py:10: error: Argument 1 to "mean_price" has incompatible type"tuple[float, float]"; expected "list[float]" [arg-type] print(mean_price((79.99, 249.0))) ^~~~~~~~~~~~~~Found 2 errors in 1 file (checked 1 source file)Pick a better parameter hint, explain in two sentences why it is safe, and make mypy --strict pass. Print both means rounded to 2 decimals.
114.33164.5Hint 1
An int is accepted as a float, so why is a list[int] not accepted as a list[float]? Think about what the function could do to the list: prices.append(0.5).
Hint 2
collections.abc.Sequence is read-only. It has no append.
Solution
"""A read-only price function accepts any sequence of numbers."""
from collections.abc import Sequence
def mean_price(prices: Sequence[float]) -> float: return sum(prices) / len(prices)
whole_dollar_prices = [79, 249, 15]print(round(mean_price(whole_dollar_prices), 2))print(round(mean_price((79.99, 249.0)), 2))
assert mean_price([1, 2, 3]) == 2.0assert round(mean_price((79.99, 249.0)), 3) == 164.495114.33164.5mypy --strict ex_c07_sequence.pySuccess: no issues found in 1 source fileHow it works:
- Choice:
Sequence[float]. Justification: the function only reads its input, andSequencepromises only reading (indexing,len, loops). Because nobody can append a float through aSequence, a list of ints or a tuple of floats is safe to pass. listis invariant:list[int]andlist[float]are unrelated types, because a function that takeslist[float]may append a float to it.Sequenceis covariant: aSequence[int]is aSequence[float], just as anintis accepted as afloat.- The tuple failed for a simpler reason: a tuple is not a list. It is a
Sequence.
Alternative: Iterable[float] is even more general (it also accepts generators), but then you cannot use len(). Use sum and a counter in one loop, or convert with list(prices) first.
M12-C08 · A Protocol for transformers
Section titled “M12-C08 · A Protocol for transformers”A preprocessing pipeline accepts any step with fit(X) and transform(X), like scikit-learn transformers. Write a runtime-checkable Transformer protocol, then two classes that match it without inheriting from it: MinMaxScaler (maps the training minimum to 0 and the maximum to 1) and Clipper(low, high) (limits each value to the range). Write run_steps(steps: list[Transformer], X: list[float]) -> list[float], which fits each step on the current data and transforms it. Clip the readings to 19.0–23.0, then scale them.
Both are Transformers: True[0.5, 0.08, 0.0, 0.6, 0.97, 1.0]from typing import Protocol, Self, runtime_checkable
readings = [21.0, 19.3, 18.7, 21.4, 22.9, 23.4]
# TODO: @runtime_checkable class Transformer(Protocol) with fit and transform
class MinMaxScaler: ... # TODO: fit stores min and max; transform maps to 0..1
class Clipper: ... # TODO: __init__(low, high); fit does nothing; transform clips
def run_steps(steps, X): # TODO: hints ...
# TODO: check isinstance for both classes, then print the result rounded to 2 decimalsHint 1
The protocol methods: def fit(self, X: list[float]) -> Self: ... and def transform(self, X: list[float]) -> list[float]: .... A fit that learns nothing still returns self.
Hint 2
Clipping: min(max(value, self.low), self.high). Scaling: (value - self.min_) / (self.max_ - self.min_).
Solution
from typing import Protocol, Self, runtime_checkable
readings = [21.0, 19.3, 18.7, 21.4, 22.9, 23.4]
@runtime_checkableclass Transformer(Protocol): def fit(self, X: list[float]) -> Self: ... def transform(self, X: list[float]) -> list[float]: ...
class MinMaxScaler: def __init__(self) -> None: self.min_ = 0.0 self.max_ = 1.0
def fit(self, X: list[float]) -> Self: self.min_, self.max_ = min(X), max(X) return self
def transform(self, X: list[float]) -> list[float]: return [(value - self.min_) / (self.max_ - self.min_) for value in X]
class Clipper: def __init__(self, low: float, high: float) -> None: self.low = low self.high = high
def fit(self, X: list[float]) -> Self: return self # nothing to learn
def transform(self, X: list[float]) -> list[float]: return [min(max(value, self.low), self.high) for value in X]
def run_steps(steps: list[Transformer], X: list[float]) -> list[float]: for step in steps: X = step.fit(X).transform(X) return X
steps: list[Transformer] = [Clipper(19.0, 23.0), MinMaxScaler()]both = all(isinstance(step, Transformer) for step in steps)print("Both are Transformers:", both)print([round(value, 2) for value in run_steps(steps, readings)])
assert run_steps([Clipper(0.0, 1.0)], [-1.0, 0.5, 2.0]) == [0.0, 0.5, 1.0]assert not isinstance(readings, Transformer)Both are Transformers: True[0.5, 0.08, 0.0, 0.6, 0.97, 1.0]How it works:
- Neither class mentions
Transformer. They match it by shape, which is structural typing. fitreturnsSelf, sostep.fit(X).transform(X)chains, likefit_transformin scikit-learn.- The clipper turns 18.7 into 19.0 and 23.4 into 23.0. The scaler then learns min 19.0 and max 23.0 from the clipped data, so 19.0 maps to 0 and 23.0 to 1.
@runtime_checkablemakes theisinstancechecks possible. They test only thatfitandtransformexist.
Alternative: an abstract base class with abc.ABC and @abstractmethod (module 19) forces subclasses to implement the methods, but every step must then inherit from it. A protocol also works for classes that you cannot change, such as scikit-learn’s.
M12-C09 · Fix the bugs: churn rules with the wrong signature
Section titled “M12-C09 · Fix the bugs: churn rules with the wrong signature”Fix the bugs: a registry of churn warning rules for data/customers.csv. Each rule must be a Rule = Callable[[CustomerRow], bool]. Two rules do not fit, and mypy says which:
"""Churn warning rules in a typed registry (2 bugs)."""
import csvfrom collections.abc import Callablefrom typing import TypedDict
class CustomerRow(TypedDict): customer_id: str contract: str tenure_months: int logins_last_30d: int
type Rule = Callable[[CustomerRow], bool]
def new_customer(row: CustomerRow) -> bool: return row["tenure_months"] <= 6
def inactive(logins: int) -> bool: return logins <= 3
def monthly_contract(row: CustomerRow) -> str: return "yes" if row["contract"] == "month-to-month" else ""
RULES: dict[str, Rule] = { "new": new_customer, "inactive": inactive, "monthly": monthly_contract,}
def load_rows(path: str) -> list[CustomerRow]: with open(path, encoding="utf-8", newline="") as f: return [ { "customer_id": r["customer_id"], "contract": r["contract"], "tenure_months": int(r["tenure_months"]), "logins_last_30d": int(r["logins_last_30d"]), } for r in csv.DictReader(f) ]
rows = load_rows("data/customers.csv")for name, rule in RULES.items(): print(f"{name:<9} {sum(rule(row) for row in rows):>5}")# TODO: fix the two rules so that every entry is a Rulemypy ex_c09_rules.pyex_c09_rules.py:32: error: Dict entry 1 has incompatible type "str": "Callable[[int], bool]";expected "str": "Callable[[CustomerRow], bool]" [dict-item] "inactive": inactive, ^~~~~~~~~~~~~~~~~~~~ex_c09_rules.py:33: error: Dict entry 2 has incompatible type "str":"Callable[[CustomerRow], str]"; expected "str": "Callable[[CustomerRow], bool]" [dict-item] "monthly": monthly_contract, ^~~~~~~~~~~~~~~~~~~~~~~~~~~Found 2 errors in 1 file (checked 1 source file)Fix both rules so that the report counts the customers that match each rule, and mypy --strict passes.
new 1110inactive 395monthly 2784Hint 1
“Dict entry 1” counts from 0: entry 1 is "inactive". Compare Callable[[int], bool] with Callable[[CustomerRow], bool]: which part differs?
Hint 2
A rule takes the whole row. monthly_contract must return a bool; a comparison already is one. (The string version would even break the count: sum() cannot add strings.)
Solution
"""Churn warning rules in a typed registry."""
import csvfrom collections.abc import Callablefrom typing import TypedDict
class CustomerRow(TypedDict): customer_id: str contract: str tenure_months: int logins_last_30d: int
type Rule = Callable[[CustomerRow], bool]
def new_customer(row: CustomerRow) -> bool: return row["tenure_months"] <= 6
def inactive(row: CustomerRow) -> bool: return row["logins_last_30d"] <= 3
def monthly_contract(row: CustomerRow) -> bool: return row["contract"] == "month-to-month"
RULES: dict[str, Rule] = { "new": new_customer, "inactive": inactive, "monthly": monthly_contract,}
def load_rows(path: str) -> list[CustomerRow]: with open(path, encoding="utf-8", newline="") as f: return [ { "customer_id": r["customer_id"], "contract": r["contract"], "tenure_months": int(r["tenure_months"]), "logins_last_30d": int(r["logins_last_30d"]), } for r in csv.DictReader(f) ]
rows = load_rows("data/customers.csv")for name, rule in RULES.items(): print(f"{name:<9} {sum(rule(row) for row in rows):>5}")
assert len(rows) == 5000assert all(isinstance(rule(rows[0]), bool) for rule in RULES.values())new 1110inactive 395monthly 2784mypy --strict ex_c09_rules_fixed.pySuccess: no issues found in 1 source fileHow it works:
inactivetook anint, but the registry calls every rule with a row. At runtime, that comparison would crash on the first row:'<=' not supported between instances of 'dict' and 'int'.monthly_contractreturned"yes"or"". Truthy strings look like booleans in anif, butsum()of strings fails. A comparison returns a realbool.sum()of booleans counts theTruevalues, becauseTrueis 1. The month-to-month count, 2,784, matches the data dictionary.- Building
CustomerRowdicts inload_rowsconverts the text fields once. The checker verifies that every key of the TypedDict is present.
M12-C10 · Interpret: mypy passes, the script crashes
Section titled “M12-C10 · Interpret: mypy passes, the script crashes”Interpret a result: this code passes mypy --strict, but it crashes. Explain why the checker did not help. Then write parse_readings(raw: object) -> list[float] that checks the parsed JSON at runtime: it must be a list, and each item an int, a float or a numeric string, which it converts. Anything else raises ValueError.
import jsonfrom typing import cast
payload = '["21.0", 21.9, 22]' # a sensor gateway sends mixed typesreadings = cast(list[float], json.loads(payload))print(sum(readings) / len(readings)) # TypeError: unsupported operand type(s) ...
def parse_readings(raw): # TODO: hints; validate and convert ...Mean: 21.63Rejected: reading 1 is not a number: TrueRejected: expected a list, got dictHint 1
What does cast check at runtime? And what type does json.loads return to the checker?
Hint 2
bool is a subtype of int, so isinstance(True, int) is True. Test for bool first and reject it. float("21.0") converts a numeric string and raises ValueError for other text.
Solution
import json
def parse_readings(raw: object) -> list[float]: """Return the readings as floats; raise ValueError for anything else.""" if not isinstance(raw, list): raise ValueError(f"expected a list, got {type(raw).__name__}") values: list[float] = [] for i, item in enumerate(raw): if isinstance(item, bool) or not isinstance(item, int | float | str): raise ValueError(f"reading {i} is not a number: {item!r}") values.append(float(item)) return values
readings = parse_readings(json.loads('["21.0", 21.9, 22]'))print(f"Mean: {sum(readings) / len(readings):.2f}")for payload in ("[21.0, true]", '{"S1": 21.0}'): try: parse_readings(json.loads(payload)) except ValueError as exc: print("Rejected:", exc)
assert readings == [21.0, 21.9, 22.0]assert all(isinstance(value, float) for value in readings)Mean: 21.63Rejected: reading 1 is not a number: TrueRejected: expected a list, got dictHow it works:
- Interpretation:
json.loadsreturnsAny, andcast(list[float], ...)tells the checker “trust me”. The checker trusted a false promise, so it had nothing to report. At runtime,summeets the string"21.0"and fails. - The fix moves the trust to a check. The parameter is
object, so the checker forces you to narrow before use:isinstance(raw, list)and thenisinstanceon each item. isinstance(item, int | float | str)accepts a union type directly (Python 3.10+). Thebooltest comes first, becauseTruewould otherwise pass as anint.float(item)converts ints and numeric strings. The text"n/a"would raiseValueErrorfromfloat()itself.
Alternative: pydantic.TypeAdapter(list[float]).validate_python(data) validates and converts in one line. It converts "21.0", but it also turns True into 1.0. With strict=True, it rejects True, and also the string "21.0". Decide which inputs you accept, then pick the mode.
M12-C11 · Validate an API error body
Section titled “M12-C11 · Validate an API error body”data/api/error_429.json is the body of a “429 Too Many Requests” response. Write a TypedDict RateLimitError with status: Literal[429], error: str, message: str, retry_after: int and remaining: int. Write parse_rate_limit(raw: dict[str, object]) -> RateLimitError that raises ValueError if a required key is missing or status is not 429. Print a retry plan from the parsed body, and show that a body without retry_after is rejected.
rate_limit_exceeded: wait 30 s (0 requests left)Rejected: missing keys ['retry_after']import jsonfrom typing import Literal, TypedDict, cast
# TODO: class RateLimitError(TypedDict)
def parse_rate_limit(raw): # TODO: hints; check keys and status ...
with open("data/api/error_429.json", encoding="utf-8") as f: body = json.load(f)# TODO: print the plan; then try a copy of body without "retry_after"Hint 1
RateLimitError.__required_keys__ is a frozenset of the required key names. Subtract raw.keys() from it to find the missing ones.
Hint 2
To build a copy without one key: {k: v for k, v in body.items() if k != "retry_after"}.
Solution
import jsonfrom typing import Literal, TypedDict, cast
class RateLimitError(TypedDict): status: Literal[429] error: str message: str retry_after: int remaining: int
def parse_rate_limit(raw: dict[str, object]) -> RateLimitError: missing = RateLimitError.__required_keys__ - raw.keys() if missing: raise ValueError(f"missing keys {sorted(missing)}") if raw["status"] != 429: raise ValueError(f"not a rate-limit error: status {raw['status']!r}") return cast(RateLimitError, raw)
with open("data/api/error_429.json", encoding="utf-8") as f: body = json.load(f)error = parse_rate_limit(body)print( f"{error['error']}: wait {error['retry_after']} s " f"({error['remaining']} requests left)")try: parse_rate_limit({k: v for k, v in body.items() if k != "retry_after"})except ValueError as exc: print("Rejected:", exc)
assert error["retry_after"] == 30assert "request_id" in body # extra keys stay in the dictrate_limit_exceeded: wait 30 s (0 requests left)Rejected: missing keys ['retry_after']How it works:
Literal[429]documents that this type describes only rate-limit errors. The runtime check enforces it for data from the network.__required_keys__comes from the TypedDict itself, so adding a key to the type automatically adds it to the check.- After both checks pass, the
castis honest. The rest of the program readserror["retry_after"]as anint. - The JSON has more keys (
limit,reset_at,request_id). The TypedDict ignores them, and they stay in the dict.
Alternative: use pydantic: TypeAdapter(RateLimitError).validate_python(body) checks the keys, the int types and the literal 429 in one call. Module 16 uses retry_after to wait and retry.
M12-C12 · A generic registry
Section titled “M12-C12 · A generic registry”Write a generic class Registry[T] that stores named items of one type: register(name, item), get(name) (raises KeyError with the list of known names for an unknown name) and names() (sorted). Use a Registry[Callable[[list[float]], float]] to store three summary functions (mean, median, max) and apply each to the readings.
['max', 'mean', 'median']max 22.1mean 21.62median 21.7KeyError: "unknown name 'p95'; known: ['max', 'mean', 'median']"from collections.abc import Callablefrom statistics import mean, median
readings = [21.0, 21.9, 21.4, 21.7, 22.1]
class Registry: # TODO: make it generic in T def __init__(self): self._items = {} # TODO: hint
# TODO: register, get, names
# TODO: create a registry of summary functions, use it, then ask for "p95"Hint 1
class Registry[T]: and inside self._items: dict[str, T] = {}. get returns T.
Hint 2
Create it with the type argument: summaries = Registry[Callable[[list[float]], float]](). Print a caught KeyError with print("KeyError:", exc).
Solution
from collections.abc import Callablefrom statistics import mean, median
readings = [21.0, 21.9, 21.4, 21.7, 22.1]
class Registry[T]: """Named items of one type, such as models, metrics or loaders."""
def __init__(self) -> None: self._items: dict[str, T] = {}
def register(self, name: str, item: T) -> None: self._items[name] = item
def get(self, name: str) -> T: if name not in self._items: raise KeyError(f"unknown name {name!r}; known: {self.names()}") return self._items[name]
def names(self) -> list[str]: return sorted(self._items)
summaries = Registry[Callable[[list[float]], float]]()summaries.register("mean", mean)summaries.register("median", median)summaries.register("max", max)print(summaries.names())for name in summaries.names(): print(name, round(summaries.get(name)(readings), 2))try: summaries.get("p95")except KeyError as exc: print("KeyError:", exc)
assert summaries.get("max")(readings) == 22.1assert Registry[int]().names() == []['max', 'mean', 'median']max 22.1mean 21.62median 21.7KeyError: "unknown name 'p95'; known: ['max', 'mean', 'median']"How it works:
Tis fixed when you create the registry. ForRegistry[Callable[[list[float]], float]],registeraccepts only such functions, andgetreturns one, so the callsummaries.get(name)(readings)is checked too.mean,medianandmaxfrom the standard library are generic or overloaded in typeshed. mypy accepts them where aCallable[[list[float]], float]is expected.- A
KeyErrorprints its message with quotes, because Python shows the repr of the key argument.
Alternative: a plain dict[str, Callable[[list[float]], float]] gives the same type safety. A class is worth it when you add behavior, such as the helpful error message here or a decorator @registry.add("name").
M12-C13 · Refactor: from TypeVar to the new syntax
Section titled “M12-C13 · Refactor: from TypeVar to the new syntax”Refactor: this pre-3.12 code uses TypeVar and Generic. Rewrite it with type parameters in brackets (def f[T], class C[T], [N: float] for the bound). Keep the behavior, add three asserts and make mypy --strict pass.
from collections.abc import Sequencefrom typing import Generic, TypeVar
K = TypeVar("K")V = TypeVar("V")N = TypeVar("N", bound=float)T = TypeVar("T")
def invert(mapping: dict[K, V]) -> dict[V, K]: """Swap keys and values: product name -> id becomes id -> name.""" return {value: key for key, value in mapping.items()}
def largest(values: Sequence[N]) -> N: best = values[0] for value in values[1:]: if value > best: best = value return best
class Labeled(Generic[T]): def __init__(self, label: str, value: T) -> None: self.label = label self.value = value
def show(self) -> str: return f"{self.label}: {self.value}"
ids = invert({"Wireless Earbuds": "P001", "Espresso Machine": "P006"})print(ids)print(largest([3, 25, 1]), largest([21.0, 22.9, 19.3]))print(Labeled("Max reading", largest([21.0, 22.9])).show())# TODO: rewrite with the PEP 695 syntax and add asserts{'P001': 'Wireless Earbuds', 'P006': 'Espresso Machine'}25 22.9Max reading: 22.9Hint 1
Delete the four TypeVar lines and the typing import. Each function or class declares its own type parameters: def invert[K, V](...).
Hint 2
bound=float becomes [N: float]. Generic[T] as a base class becomes class Labeled[T]:.
Solution
"""Generic helpers in the Python 3.12 syntax."""
from collections.abc import Sequence
def invert[K, V](mapping: dict[K, V]) -> dict[V, K]: """Swap keys and values: product name -> id becomes id -> name.""" return {value: key for key, value in mapping.items()}
def largest[N: float](values: Sequence[N]) -> N: """Return the largest value; N is float, int or a subtype.""" best = values[0] for value in values[1:]: if value > best: best = value return best
class Labeled[T]: """A value with a human-readable label for a report."""
def __init__(self, label: str, value: T) -> None: self.label = label self.value = value
def show(self) -> str: return f"{self.label}: {self.value}"
ids = invert({"Wireless Earbuds": "P001", "Espresso Machine": "P006"})print(ids)print(largest([3, 25, 1]), largest([21.0, 22.9, 19.3]))print(Labeled("Max reading", largest([21.0, 22.9])).show())
assert ids["P006"] == "Espresso Machine"assert largest([3, 25, 1]) == 25assert Labeled("n", 5).value == 5{'P001': 'Wireless Earbuds', 'P006': 'Espresso Machine'}25 22.9Max reading: 22.9mypy --strict ex_c13_generics.pySuccess: no issues found in 1 source fileHow it works:
- Each type parameter now lives in the brackets of the function or class that uses it. No module-level
K,V,NorTremain to be reused by mistake. - The bound
[N: float]letslargestcompare values with>: everyfloat(andint) supports it. Forlargest([3, 25, 1]),Nisint, so the result is anint, not just a float. class Labeled[T]:replaces theGeneric[T]base class. Behavior and output are unchanged: the refactor touches only the declarations.- Ruff’s
UP046andUP047rules flag the old form.ruff check --fix --unsafe-fixesapplies the rewrite. Ruff marks the fix unsafe because the new syntax infers variance, so review the result.
Challenge
Section titled “Challenge”M12-X01 · Region summaries from nested JSON
Section titled “M12-X01 · Region summaries from nested JSON”Use the lesson’s customer_types.py. Write a TypedDict RegionSummary with customers, orders, spend and top_customer, and summarize_regions(customers: list[Customer]) -> dict[str, RegionSummary]. Group the 20 customers of data/customers.json by address.region, count their orders, sum their order amounts and find the customer with the highest spend. Print a table sorted by region. mypy --strict must pass.
Region Customers Orders Spend Top customerEast 6 10 2,900.85 Omar FaroukNorth 7 18 5,097.14 Mateo LopezSouth 4 11 2,198.45 Ravi PatelWest 3 9 3,515.26 Mei Chenfrom pathlib import Pathfrom typing import TypedDict
from customer_types import Customer, load_export
class RegionSummary(TypedDict): ... # TODO: four keys
def spend(customer: Customer) -> float: ... # TODO
def summarize_regions(customers: list[Customer]) -> dict[str, RegionSummary]: ... # TODO: group by region, then build one RegionSummary per region
customers = load_export(Path("data/customers.json"))["customers"]# TODO: print the tableHint 1
Group first: groups: dict[str, list[Customer]] = {} and groups.setdefault(region, []).append(customer).
Hint 2
max(members, key=spend) returns the top customer of a group. Build each summary as a dict literal; mypy checks it against RegionSummary because of the return hint.
Hint 3
Header and rows use the same widths: {region:<7} {customers:>9} {orders:>6} {spend:>10,.2f}.
Solution
"""Summarize data/customers.json per region into typed records."""
from pathlib import Pathfrom typing import TypedDict
from customer_types import Customer, load_export
class RegionSummary(TypedDict): customers: int orders: int spend: float top_customer: str
def spend(customer: Customer) -> float: return sum(order["amount"] for order in customer["orders"])
def summarize_regions(customers: list[Customer]) -> dict[str, RegionSummary]: groups: dict[str, list[Customer]] = {} for customer in customers: groups.setdefault(customer["address"]["region"], []).append(customer) summaries: dict[str, RegionSummary] = {} for region, members in sorted(groups.items()): top = max(members, key=spend) summaries[region] = { "customers": len(members), "orders": sum(len(c["orders"]) for c in members), "spend": round(sum(spend(c) for c in members), 2), "top_customer": top["name"], } return summaries
customers = load_export(Path("data/customers.json"))["customers"]summaries = summarize_regions(customers)print(f"{'Region':<7} {'Customers':>9} {'Orders':>6} {'Spend':>10} Top customer")for region, s in summaries.items(): print( f"{region:<7} {s['customers']:>9} {s['orders']:>6} {s['spend']:>10,.2f}" f" {s['top_customer']}" )
assert sum(s["customers"] for s in summaries.values()) == 20assert sum(s["orders"] for s in summaries.values()) == 48Region Customers Orders Spend Top customerEast 6 10 2,900.85 Omar FaroukNorth 7 18 5,097.14 Mateo LopezSouth 4 11 2,198.45 Ravi PatelWest 3 9 3,515.26 Mei Chenmypy --strict ex_x01_regions.pySuccess: no issues found in 1 source fileHow it works:
- The input type (
Customer) and the output type (RegionSummary) are both TypedDicts, so every key read and every key written is checked. - Grouping first and summarizing second keeps each step simple.
sorted(groups.items())orders the regions alphabetically. max(members, key=spend)reuses thespendfunction as a key. It returns aCustomer, sotop["name"]is a checkedstr.- The asserts check two facts from the data dictionary: 20 customers and 48 orders in total. Three customers have no orders and add 0 to their region.
Alternative: load the records into pandas with pd.json_normalize(customers, "orders", ["customer_id", ["address", "region"]]) and use groupby (module 25). The typed version is better for a small library function that other code calls; pandas is better for exploration.
M12-X02 · Type a decorator that keeps the signature
Section titled “M12-X02 · Type a decorator that keeps the signature”A decorator (module 11) that counts calls and adds up run time must not hide the signature of the function it wraps. Write timed with the PEP 695 syntax def timed[**P, R](func: Callable[P, R]) -> Callable[P, R], where **P is a ParamSpec (a type parameter that stands for a whole parameter list). It stores the call count in CALLS and the total seconds in SECONDS (do not print timings: they change on every run). Decorate scale(data: list[float], factor: float = 1.0) -> list[float]. Then check with mypy that a wrong argument to the decorated function is still caught.
[37.8, 39.42][0.5, 1.0]scale called 2 timesimport functoolsimport timefrom collections.abc import Callable
CALLS: dict[str, int] = {}SECONDS: dict[str, float] = {}
def timed(func): # TODO: def timed[**P, R](func: Callable[P, R]) -> Callable[P, R] @functools.wraps(func) def wrapper(*args, **kwargs): # TODO: hints with P.args, P.kwargs and R ... # TODO: time the call, count it, return the result
return wrapper
@timeddef scale(data: list[float], factor: float = 1.0) -> list[float]: return [round(value * factor, 2) for value in data]
# TODO: call scale twice and print the countHint 1
Inside, the wrapper’s signature is def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:. This tells the checker that the wrapper accepts exactly the parameters of func.
Hint 2
Use try: / return func(*args, **kwargs) / finally: so the call is counted even when func raises.
Hint 3
To check the signature, write a second file that imports scale, calls reveal_type(scale) and makes one bad call such as factor="1.8". Run mypy on it; do not run it with Python.
Solution
"""A call-counting decorator that keeps the signature of the function."""
import functoolsimport timefrom collections.abc import Callable
CALLS: dict[str, int] = {}SECONDS: dict[str, float] = {}
def timed[**P, R](func: Callable[P, R]) -> Callable[P, R]: """Count the calls and add up the run time of `func`."""
@functools.wraps(func) def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: start = time.perf_counter() try: return func(*args, **kwargs) finally: CALLS[func.__name__] = CALLS.get(func.__name__, 0) + 1 SECONDS[func.__name__] = SECONDS.get(func.__name__, 0.0) + ( time.perf_counter() - start )
return wrapper
@timeddef scale(data: list[float], factor: float = 1.0) -> list[float]: return [round(value * factor, 2) for value in data]
print(scale([21.0, 21.9], 1.8))print(scale([1.0, 2.0], factor=0.5))print(scale.__name__, "called", CALLS["scale"], "times")
assert CALLS["scale"] == 2assert SECONDS["scale"] >= 0.0[37.8, 39.42][0.5, 1.0]scale called 2 timesThe check file, for mypy only:
"""What mypy sees after decoration."""
from typing import reveal_type
from ex_x02_timed import scale
reveal_type(scale)scale([21.0, 21.9], factor="1.8")mypy --strict ex_x02_timed.pymypy ex_x02_check.pySuccess: no issues found in 1 source fileex_x02_check.py:7: note: Revealed type is "def (data: list[float], factor: float =) -> list[float]"ex_x02_check.py:8: error: Argument "factor" to "scale" has incompatible type "str"; expected"float" [arg-type] scale([21.0, 21.9], factor="1.8") ^~~~~Found 1 error in 1 file (checked 1 source file)How it works:
Pcaptures the parameter list offunc(names, types, defaults) andRits return type.Callable[P, R]in the return hint says “the result has the same signature”.reveal_type(scale)shows the original signature after decoration, and the bad keyword argument is caught. With a naive hint such asCallable[..., Any], mypy would reveal a function that accepts anything and returnsAny, and the bad call would pass.functools.wrapscopies__name__and the docstring at runtime; the hints copy the signature for the checker. You need both.try/finallyrecords the call even whenfuncraises. Timings go intoSECONDSinstead of the output, so the output stays the same on every run.
Alternative: before Python 3.12, the same decorator needs P = ParamSpec("P") and R = TypeVar("R") from typing at module level. The bodies are identical.
M12-X03 · Overloads for a typed field parser
Section titled “M12-X03 · Overloads for a typed field parser”CSV fields arrive as text. Write parse_field(text, kind) where kind is "int", "float" or "bool" (a 0/1 flag). Use @overload so that the return type follows the kind: int, float or bool. An invalid flag raises ValueError. Parse tenure_months, monthly_charges and has_autopay of the first row of data/customers.csv (read it with readline() and split(",")), and print them and their product. Check with reveal_type that mypy picks the right overload and rejects an unknown kind.
C00001 72 84.69 FalseCharges times tenure: 6,097.68from typing import Literal, overload
type Kind = Literal["int", "float", "bool"]
# TODO: three @overload signatures, one per kinddef parse_field(text, kind): # TODO: implementation signature ...
with open("data/customers.csv", encoding="utf-8") as f: header = f.readline().strip().split(",") first = dict(zip(header, f.readline().strip().split(","), strict=True))# TODO: parse three fields and print the two linesHint 1
Each overload uses a one-value Literal for kind: def parse_field(text: str, kind: Literal["int"]) -> int: ....
Hint 2
The real implementation comes last, without @overload, and covers all cases: def parse_field(text: str, kind: Kind) -> int | float | bool:.
Solution
"""Parse CSV fields with a return type that follows the requested kind."""
from typing import Literal, overload
type Kind = Literal["int", "float", "bool"]
@overloaddef parse_field(text: str, kind: Literal["int"]) -> int: ...@overloaddef parse_field(text: str, kind: Literal["float"]) -> float: ...@overloaddef parse_field(text: str, kind: Literal["bool"]) -> bool: ...def parse_field(text: str, kind: Kind) -> int | float | bool: if kind == "int": return int(text) if kind == "float": return float(text) if text not in ("0", "1"): raise ValueError(f"not a 0/1 flag: {text!r}") return text == "1"
with open("data/customers.csv", encoding="utf-8") as f: header = f.readline().strip().split(",") first = dict(zip(header, f.readline().strip().split(","), strict=True))
tenure = parse_field(first["tenure_months"], "int")charges = parse_field(first["monthly_charges"], "float")autopay = parse_field(first["has_autopay"], "bool")print(first["customer_id"], tenure, charges, autopay)print(f"Charges times tenure: {tenure * charges:,.2f}")
assert (tenure, autopay) == (72, False)assert isinstance(charges, float)C00001 72 84.69 FalseCharges times tenure: 6,097.68"""Which return type does mypy pick for each call?"""
from typing import reveal_type
from ex_x03_fields import parse_field
reveal_type(parse_field("72", "int"))reveal_type(parse_field("84.69", "float"))reveal_type(parse_field("0", "bool"))parse_field("72", "date")mypy --strict ex_x03_fields.pymypy ex_x03_check.pySuccess: no issues found in 1 source fileex_x03_check.py:7: note: Revealed type is "int"ex_x03_check.py:8: note: Revealed type is "float"ex_x03_check.py:9: note: Revealed type is "bool"ex_x03_check.py:10: error: No overload variant of "parse_field" matches argument types "str", "str" [call-overload] parse_field("72", "date") ^~~~~~~~~~~~~~~~~~~~~~~~~ex_x03_check.py:10: note: Possible overload variants:ex_x03_check.py:10: note: def parse_field(text: str, kind: Literal['int']) -> intex_x03_check.py:10: note: def parse_field(text: str, kind: Literal['float']) -> floatex_x03_check.py:10: note: def parse_field(text: str, kind: Literal['bool']) -> boolFound 1 error in 1 file (checked 1 source file)How it works:
- The three overloads are only signatures. mypy picks the first one whose parameter types match the call, so
"int"selects-> int. - Because
tenureis anintandchargesafloat,tenure * chargesis checked as a float multiplication. Without overloads, both would beint | float | bool, and every use would need anisinstancecheck. - The implementation is not visible to callers. It must accept every case the overloads describe; mypy checks that it is compatible with them.
- For
"date", no overload matches, and mypy lists the valid variants.
Alternative: three small functions (parse_int, parse_float, parse_flag) need no overloads at all. Overloads pay off when one entry point is part of a public API, as with pandas.read_csv, which returns a DataFrame or a reader object depending on its chunksize argument.
M12-X04 · Pick the best model through a Protocol
Section titled “M12-X04 · Pick the best model through a Protocol”Use the lesson’s models.py. Write a third model, LinearSqftRegressor, that fits a least-squares line price = slope × sqft + intercept in pure Python and matches the Regressor protocol. Then write select_best(models: dict[str, Regressor], X, y, n_train, metric: Metric = mae) -> tuple[str, dict[str, float]], which fits each model on the first n_train houses and returns the name of the model with the lowest metric and all scores. Print the scores from best to worst. mypy --strict must pass.
linear MAE 154,798per_sqft MAE 158,325mean MAE 225,400Best: linearfrom collections.abc import Callable, Sequencefrom typing import Self
from models import ( Features, MeanRegressor, PricePerSqftRegressor, Regressor, load_houses, mae,)
type Metric = Callable[[Sequence[float], Sequence[float]], float]
class LinearSqftRegressor: ... # TODO: __init__, fit (least squares on row[0]), predict
def select_best(models, X, y, n_train, metric=mae): # TODO: hints ...
X, y = load_houses("data/houses.csv")# TODO: build the candidates dict, select, printHint 1
For one feature, slope = Σ(x − x̄)(y − ȳ) / Σ(x − x̄)², and intercept = ȳ − slope × x̄.
Hint 2
Hint the candidates dict explicitly: candidates: dict[str, Regressor] = {...}. Without it, mypy infers a dict of the common base type of the three classes, which is object.
Solution
"""Pick the best of several models that follow the Regressor protocol."""
from collections.abc import Callable, Sequencefrom typing import Self
from models import ( Features, MeanRegressor, PricePerSqftRegressor, Regressor, load_houses, mae,)
type Metric = Callable[[Sequence[float], Sequence[float]], float]
class LinearSqftRegressor: """Least-squares line on the first feature: price = slope * sqft + intercept."""
def __init__(self) -> None: self.slope_ = 0.0 self.intercept_ = 0.0
def fit(self, X: Features, y: Sequence[float]) -> Self: xs = [row[0] for row in X] x_mean, y_mean = sum(xs) / len(xs), sum(y) / len(y) cov = sum((a - x_mean) * (b - y_mean) for a, b in zip(xs, y, strict=True)) var = sum((a - x_mean) ** 2 for a in xs) self.slope_ = cov / var self.intercept_ = y_mean - self.slope_ * x_mean return self
def predict(self, X: Features) -> list[float]: return [self.slope_ * row[0] + self.intercept_ for row in X]
def select_best( models: dict[str, Regressor], X: Features, y: Sequence[float], n_train: int, metric: Metric = mae,) -> tuple[str, dict[str, float]]: """Fit every model on the first n_train rows; lower metric is better.""" scores: dict[str, float] = {} for name, model in models.items(): model.fit(X[:n_train], y[:n_train]) scores[name] = metric(y[n_train:], model.predict(X[n_train:])) best = min(scores, key=lambda name: scores[name]) return best, scores
X, y = load_houses("data/houses.csv")candidates: dict[str, Regressor] = { "mean": MeanRegressor(), "per_sqft": PricePerSqftRegressor(), "linear": LinearSqftRegressor(),}best, scores = select_best(candidates, X, y, n_train=2400)for name, value in sorted(scores.items(), key=lambda item: item[1]): print(f"{name:<9} MAE {value:>10,.0f}")print("Best:", best)
assert best == min(scores, key=lambda name: scores[name])assert isinstance(LinearSqftRegressor(), Regressor)linear MAE 154,798per_sqft MAE 158,325mean MAE 225,400Best: linearmypy --strict ex_x04_select.pySuccess: no issues found in 1 source fileHow it works:
LinearSqftRegressormatchesRegressorby shape. Nothing inmodels.pyhad to change to accept it: this is the main benefit of a protocol.select_bestdepends only on the protocol and on theMetricalias, so any metric with the right signature (rmse,mape) can replacemae.- The line fit gives the same MAE (154,798) as scikit-learn’s
LinearRegressionin the lesson, because both solve the same least-squares problem. min(scores, key=lambda name: scores[name])avoidskey=scores.get, which mypy rejects becausegetmay returnNone.
Alternative: make select_best generic, def select_best[M: Regressor](models: dict[str, M], ...) -> tuple[str, M], and return the best fitted model itself. The bound M: Regressor keeps the specific class, so the caller can read best_model.slope_ when all candidates are LinearSqftRegressor objects.
M12-X05 · Stream all API pages with a typed generator
Section titled “M12-X05 · Stream all API pages with a typed generator”The product API is paginated: each page has next, the URL of the next page or null. Using the lesson’s product_types.py, write iter_products(first: Path) -> Iterator[Product], a generator that follows next across the saved pages (?page=2 maps to data/api/products_page_2.json). Then collect all products and print the count, the out-of-stock ids and the mean rating per category. mypy --strict must pass.
30 productsOut of stock: ['P006', 'P019']Beauty 3.86Books 3.90Clothing 3.76Electronics 3.84Home 3.82Sports 3.94from collections.abc import Iteratorfrom pathlib import Pathfrom urllib.parse import parse_qs, urlparse
from product_types import Product, load_page
def page_file(url: str) -> Path: ... # TODO: read the page number from the query string
def iter_products(first: Path) -> Iterator[Product]: ... # TODO: load a page, yield its products, follow "next" until None
def mean_rating_by_category(products: list[Product]) -> dict[str, float]: ... # TODO: rounded to 2 decimals, categories sorted
# TODO: collect the products and print the three linesHint 1
parse_qs(urlparse(url).query) returns {"page": ["2"], "per_page": ["10"]}.
Hint 2
Keep the current file in a variable typed Path | None. Loop while path is not None:; inside the loop, the checker knows that path is a Path.
Hint 3
page["next"] is str | None. Narrow it before you call page_file: path = None if next_url is None else page_file(next_url).
Solution
"""Stream every product from the saved API pages by following `next`."""
from collections.abc import Iteratorfrom pathlib import Pathfrom urllib.parse import parse_qs, urlparse
from product_types import Product, load_page
def page_file(url: str) -> Path: """Map an API URL to its saved fixture: ?page=2 -> products_page_2.json.""" page = parse_qs(urlparse(url).query)["page"][0] return Path(f"data/api/products_page_{page}.json")
def iter_products(first: Path) -> Iterator[Product]: """Yield the products of every page, one page file at a time.""" path: Path | None = first while path is not None: page = load_page(path) yield from page["data"] next_url = page["next"] path = None if next_url is None else page_file(next_url)
def mean_rating_by_category(products: list[Product]) -> dict[str, float]: ratings: dict[str, list[float]] = {} for product in products: ratings.setdefault(product["category"], []).append(product["rating"]["average"]) return {cat: round(sum(r) / len(r), 2) for cat, r in sorted(ratings.items())}
products = list(iter_products(Path("data/api/products_page_1.json")))print(len(products), "products")print("Out of stock:", [p["id"] for p in products if not p["in_stock"]])for category, rating in mean_rating_by_category(products).items(): print(f"{category:<12} {rating:.2f}")
assert len({p["id"] for p in products}) == 30assert page_file("https://api.example.com/v1/products?page=3&per_page=10").name == ( "products_page_3.json")30 productsOut of stock: ['P006', 'P019']Beauty 3.86Books 3.90Clothing 3.76Electronics 3.84Home 3.82Sports 3.94mypy --strict ex_x05_pages.pySuccess: no issues found in 1 source fileHow it works:
iter_productsis a generator, so its return type isIterator[Product](module 10).yield from page["data"]yields each product of a page, and the caller sees one flat stream.path: Path | Noneneeds its hint: it starts as aPathand becomesNoneat the end. Thewhile path is not Nonecondition narrows it inside the loop.next: str | NoneinProductPageforces theNonecheck beforepage_file. Forgetting it is a mypy error (Argument 1 to "page_file" has incompatible type "str | None"), not a crash on the last page.- The real API version replaces
load_page(path)with an HTTP request (module 16). The types and the loop stay the same.
Alternative: loop over sorted(Path("data/api").glob("products_page_*.json")). It is simpler for saved files, but it ignores next, so it cannot work against a live API where you do not know the number of pages.