Skip to content

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:

  1. Read the task and the expected output.
  2. 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.
  3. Run it with python file.py. For the exercises that use mypy, also run mypy file.py or mypy --strict file.py, as the task says.
  4. 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

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__.

Expected output
Total: 771.27
quantities: list[int]
unit_prices: list[float]
discount: <class 'float'>
return: <class 'float'>
Starter
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.27
assert order_total([1], [10.0]) == 10.0
assert order_total.__annotations__["return"] is float
Output
Total: 771.27
quantities: list[int]
unit_prices: list[float]
discount: <class 'float'>
return: <class 'float'>

How it works:

  1. Each parameter gets name: type, and the return type follows ->.
  2. 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.
  3. __annotations__ stores the hints as objects. A plain class prints as <class 'float'>; a generic such as list[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”
Warm-up

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.
Starter
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 it
Hint 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 call
assert double_units([1, 2]) == [1, 2, 1, 2]
Output
42
2121
5.0
[1, 2, 1, 2]

How it works:

  1. 21 * 2 is 42, as intended.
  2. "21" * 2 repeats the string: "2121". No error, and the result is wrong. This is the typical bug when a number arrives as text from a file.
  3. 2.5 * 2 is 5.0, a float although the hint promises an int.
  4. [1, 2] * 2 repeats the list.
  5. mypy rejects the second, third and fourth calls: each argument is not an int. Python accepts all four.
Warm-up

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.

Expected output
Totals: {'S01': 7, 'S02': 9, 'S03': 4}
Best: ('S02', 9)
Starter
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 store
Hint 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)
Output
Totals: {'S01': 7, 'S02': 9, 'S03': 4}
Best: ('S02', 9)

How it works:

  1. dict[str, list[int]] says: store ids are strings, and each value is a list of whole-number quantities.
  2. The comprehension builds dict[str, int], one total per store.
  3. max with a key function compares the pairs by their second item. dict.items() yields tuple[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”
Warm-up

Fix the bug: this price lookup claims to always return a float, but dict.get() returns None for an unknown id. mypy reports it:

ex_w04_lookup.py (starter)
"""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 caller
Terminal
mypy ex_w04_lookup.py
Output
ex_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.

Expected output
P001: 79.99
P999: unknown
Hint 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
ex_w04_lookup_fixed.py
"""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.0
assert price_of("P999") is None
Output
P001: 79.99
P999: unknown
Terminal
mypy --strict ex_w04_lookup_fixed.py
Output
Success: no issues found in 1 source file

How it works:

  1. PRICES.get(product_id) has the type float | None, so the honest return hint is float | None.
  2. The caller now must handle None. Inside the else branch, mypy has narrowed price to float, so :.2f is safe.
  3. Without the is None check, f"{price:.2f}" would crash at runtime for P999 with TypeError: 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.

Warm-up

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.

Expected output
standard 659.88
premium 1079.88
ValueError: unknown plan 'gold'; expected one of ('basic', 'standard', 'premium')
Starter
from typing import Literal, cast, get_args
type Plan = ... # TODO: the three plan names
MONTHLY_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.88
assert parse_plan("PREMIUM ") == "premium"
Output
standard 659.88
premium 1079.88
ValueError: unknown plan 'gold'; expected one of ('basic', 'standard', 'premium')

How it works:

  1. The alias lists the three valid plans once. The fee table and both functions reuse it.
  2. annual_fee("gold") would fail the type check. Text from a file is only a str, so parse_plan checks it at runtime.
  3. 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”
Warm-up

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.

Expected output
file: clean_readings.py
line: 27
severity: error
msg: Argument 1 to "summarize" has incompatible type "list[float | None]"; expected "list[float]"
code: arg-type
Starter
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): # TODO: hints
# TODO: split off the file, line and severity; then the code in [...]
...
# TODO: print the five parts with their labels
Hint 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] == 27
assert parts[4] == "arg-type"
Output
file: clean_readings.py
line: 27
severity: error
msg: Argument 1 to "summarize" has incompatible type "list[float | None]"; expected "list[float]"
code: arg-type

How it works:

  1. Interpretation: at line 27 of clean_readings.py, a list[float | None] is passed to summarize, which accepts only list[float]. The list still contains the None values of the broken lines. The code arg-type means “an argument has the wrong type”.
  2. split(": ", 2) makes at most two cuts, so colons inside the message stay in rest.
  3. mypy puts two spaces before the code in brackets. rsplit(" [", 1) cuts only at the last occurrence.
  4. 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.

Warm-up

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”.

Expected output
Out of range: [2, 5]
Below 20.0: [1, 2]
Starter
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 positions
Hint 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) == []
Output
Out of range: [2, 5]
Below 20.0: [1, 2]

How it works:

  1. Callable[[float], bool] accepts any function with one float parameter and a bool result: a named function or a lambda.
  2. enumerate pairs each reading with its position, and the condition keeps the positions where the rule says True.
  3. The checker infers the lambda’s parameter type from the hint, so c is a float inside 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”
Warm-up

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 type notes in the solution.
  • You can explain the third one: why is there a None?
ex_w08_reveal.py (starter)
"""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
Terminal
mypy ex_w08_reveal.py
Output
ex_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 file

The 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 None
assert isinstance(len(ids) / 2, float)
Output
NoneType float ['P001', 'P002']

How it works:

  1. The dict literal has str keys and float values, so it is a dict[str, float]. sorted() returns a list of its keys: list[str].
  2. prices.get("P003") returns None when the key is missing. mypy does not know which keys exist, so the type is float | None.
  3. / gives a float even for two ints. A comparison gives a bool, so the comprehension is a list[bool].
  4. Notes are not errors, so the run ends with Success.
Core

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.

Expected output
Page 2: 10 products
Best rated: Adjustable Dumbbells (4.3 from 53 reviews)
Out of stock: ['P019']
Starter
import json
from 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 lines
Hint 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 json
from 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) == 10
assert all(p["price"]["currency"] == "USD" for p in products)
Output
Page 2: 10 products
Best rated: Adjustable Dumbbells (4.3 from 53 reviews)
Out of stock: ['P019']

How it works:

  1. One TypedDict per JSON object. Nesting in the JSON becomes nesting in the types.
  2. cast(Page, json.load(f)) turns the Any from json.load into a typed value. From here on, the editor completes keys and the checker rejects typos.
  3. The key function reads two levels deep. The checker knows that p["rating"]["average"] is a float, so max can 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”
Core

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:

ex_c02_weather.py (starter)
"""Summarize the hourly forecast in data/api/weather_forecast.json (2 bugs)."""
import json
from pathlib import Path
from 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 passes
Terminal
mypy ex_c02_weather.py
Output
ex_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.

Expected output
10 rainy hours, from 2024-05-02T00:00 to 2024-05-02T09:00
Max wind: 27.3 km/h
Hint 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
ex_c02_weather_fixed.py
"""Summarize the hourly forecast in data/api/weather_forecast.json."""
import json
from pathlib import Path
from 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) == 10
assert all(h["temperature_c"] > -50 for h in hours)
Output
10 rainy hours, from 2024-05-02T00:00 to 2024-05-02T09:00
Max wind: 27.3 km/h
Terminal
mypy --strict ex_c02_weather_fixed.py
Output
Success: no issues found in 1 source file

How it works:

  1. Error 1 names the missing key and the TypedDict. The JSON key is precipitation_probability. At runtime, this bug is a KeyError on the first hour.
  2. Errors 2 and 3 come from one bug. max needs values it can compare; a Wind dict is not one. And even if it worked, the result would be a Wind, not the promised float. Reading ["speed_kmh"] fixes both.
  3. One wrong line often produces several messages. Fix the first error on a line, then run mypy again.
  4. Forecast describes only hourly, although the JSON also has location, daily and more. A TypedDict needs only the keys your code uses.
Core

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.

Expected output
C03991: 6.4 min
C00002: 15.1 min
C04995: no data
Starter
sessions = {
"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 customer
Hint 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 None
assert mean_or_none([0.0, None]) == 0.0
Output
C03991: 6.4 min
C00002: 15.1 min
C04995: no data

How it works:

  1. The comprehension with is not None removes the gaps and narrows the type to list[float], so sum is safe.
  2. “No known value” is a real outcome, so the return hint says float | None. Returning 0.0 would claim a session time of zero.
  3. describe handles both cases. Inside the conditional expression, the checker knows that value is a float in the else part.
  4. The second assert checks that a real 0.0 is kept: a test with if v instead of is not None would 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”
Core

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.

ex_c04_untyped.py (starter)
"""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 output
Terminal
mypy --strict ex_c04_untyped.py | grep error
Output
ex_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 context
ex_c04_untyped.py:20: error: Call to untyped function "top_categories" in typed context
Found 5 errors in 1 file (checked 1 source file)
Expected output
Electronics 1,808,108.17
Home 672,294.61
Sports 544,108.55
Hint 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
ex_c04_typed.py
"""Revenue per category from data/sales.csv, with full hints."""
import csv
from 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.83
Output
Electronics 1,808,108.17
Home 672,294.61
Sports 544,108.55
Terminal
mypy --strict ex_c04_typed.py
Output
Success: no issues found in 1 source file

How it works:

  1. Annotating both functions fixes four errors: the two missing annotations and the two “untyped call” errors at the bottom.
  2. totals: dict[str, float] = {} fixes the fifth. An empty dict alone tells mypy nothing about its keys and values.
  3. key=totals.get was fine for Python but not for the checker: get returns float | None, and sorted cannot compare None. The lambda totals[category] always returns a float. mypy found this only after the dict had a type.
  4. Iterable[dict[str, str]] accepts the DictReader and 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).

Core

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.

Expected output
Last reading: 22.1
Last product: ('P006', 349.0)
Top 2 readings: [22.1, 21.9]
Top 2 products by price: [('P006', 349.0), ('P002', 249.0)]
Starter
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 lines
Hint 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) == []
Output
Last reading: 22.1
Last 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:

  1. T links the input to the output. For last(products), T is tuple[str, float], so the checker knows that last(products)[1] is a float.
  2. In top_n, T appears three times: in the items, in the key function’s parameter and in the result. The checker infers T from the items and then checks the lambda against Callable[[T], float].
  3. last needs indexing, so it takes a Sequence. top_n only loops, so it takes any Iterable, 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”
Core

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.

Expected output
[1.54, 1.51]
[-0.38, -0.9]
[-1.21, -0.9]
[0.05, 0.3]
Starter
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 row
Hint 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
Output
[1.54, 1.51]
[-0.38, -0.9]
[-1.21, -0.9]
[0.05, 0.3]

How it works:

  1. The aliases name the shapes of the data, so standardize(X: Matrix) -> Matrix reads as “a matrix in, a matrix out”.
  2. zip(*X) transposes the rows into columns. Each column gets its mean and population standard deviation.
  3. Each value becomes its distance from the column mean in standard deviations. This is what scikit-learn’s StandardScaler does (module 33).
  4. To the checker, Matrix is exactly list[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]”
Core

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.)

ex_c07_invariance.py (starter)
"""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 it
Terminal
mypy ex_c07_invariance.py | grep -v "https://"
Output
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 covariant
ex_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.

Expected output
114.33
164.5
Hint 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
ex_c07_sequence.py
"""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.0
assert round(mean_price((79.99, 249.0)), 3) == 164.495
Output
114.33
164.5
Terminal
mypy --strict ex_c07_sequence.py
Output
Success: no issues found in 1 source file

How it works:

  1. Choice: Sequence[float]. Justification: the function only reads its input, and Sequence promises only reading (indexing, len, loops). Because nobody can append a float through a Sequence, a list of ints or a tuple of floats is safe to pass.
  2. list is invariant: list[int] and list[float] are unrelated types, because a function that takes list[float] may append a float to it. Sequence is covariant: a Sequence[int] is a Sequence[float], just as an int is accepted as a float.
  3. 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.

Core

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.

Expected output
Both are Transformers: True
[0.5, 0.08, 0.0, 0.6, 0.97, 1.0]
Starter
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 decimals
Hint 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_checkable
class 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)
Output
Both are Transformers: True
[0.5, 0.08, 0.0, 0.6, 0.97, 1.0]

How it works:

  1. Neither class mentions Transformer. They match it by shape, which is structural typing.
  2. fit returns Self, so step.fit(X).transform(X) chains, like fit_transform in scikit-learn.
  3. 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.
  4. @runtime_checkable makes the isinstance checks possible. They test only that fit and transform exist.

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”
Core

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:

ex_c09_rules.py (starter)
"""Churn warning rules in a typed registry (2 bugs)."""
import csv
from collections.abc import Callable
from 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 Rule
Terminal
mypy ex_c09_rules.py
Output
ex_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.

Expected output
new 1110
inactive 395
monthly 2784
Hint 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
ex_c09_rules_fixed.py
"""Churn warning rules in a typed registry."""
import csv
from collections.abc import Callable
from 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) == 5000
assert all(isinstance(rule(rows[0]), bool) for rule in RULES.values())
Output
new 1110
inactive 395
monthly 2784
Terminal
mypy --strict ex_c09_rules_fixed.py
Output
Success: no issues found in 1 source file

How it works:

  1. inactive took an int, 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'.
  2. monthly_contract returned "yes" or "". Truthy strings look like booleans in an if, but sum() of strings fails. A comparison returns a real bool.
  3. sum() of booleans counts the True values, because True is 1. The month-to-month count, 2,784, matches the data dictionary.
  4. Building CustomerRow dicts in load_rows converts 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”
Core

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.

Starter
import json
from typing import cast
payload = '["21.0", 21.9, 22]' # a sensor gateway sends mixed types
readings = 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
...
Expected output
Mean: 21.63
Rejected: reading 1 is not a number: True
Rejected: expected a list, got dict
Hint 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)
Output
Mean: 21.63
Rejected: reading 1 is not a number: True
Rejected: expected a list, got dict

How it works:

  1. Interpretation: json.loads returns Any, and cast(list[float], ...) tells the checker “trust me”. The checker trusted a false promise, so it had nothing to report. At runtime, sum meets the string "21.0" and fails.
  2. 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 then isinstance on each item.
  3. isinstance(item, int | float | str) accepts a union type directly (Python 3.10+). The bool test comes first, because True would otherwise pass as an int.
  4. float(item) converts ints and numeric strings. The text "n/a" would raise ValueError from float() 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.

Core

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.

Expected output
rate_limit_exceeded: wait 30 s (0 requests left)
Rejected: missing keys ['retry_after']
Starter
import json
from 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 json
from 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"] == 30
assert "request_id" in body # extra keys stay in the dict
Output
rate_limit_exceeded: wait 30 s (0 requests left)
Rejected: missing keys ['retry_after']

How it works:

  1. Literal[429] documents that this type describes only rate-limit errors. The runtime check enforces it for data from the network.
  2. __required_keys__ comes from the TypedDict itself, so adding a key to the type automatically adds it to the check.
  3. After both checks pass, the cast is honest. The rest of the program reads error["retry_after"] as an int.
  4. 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.

Core

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.

Expected output
['max', 'mean', 'median']
max 22.1
mean 21.62
median 21.7
KeyError: "unknown name 'p95'; known: ['max', 'mean', 'median']"
Starter
from collections.abc import Callable
from 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 Callable
from 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.1
assert Registry[int]().names() == []
Output
['max', 'mean', 'median']
max 22.1
mean 21.62
median 21.7
KeyError: "unknown name 'p95'; known: ['max', 'mean', 'median']"

How it works:

  1. T is fixed when you create the registry. For Registry[Callable[[list[float]], float]], register accepts only such functions, and get returns one, so the call summaries.get(name)(readings) is checked too.
  2. mean, median and max from the standard library are generic or overloaded in typeshed. mypy accepts them where a Callable[[list[float]], float] is expected.
  3. A KeyError prints 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”
Core

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.

Starter (old style)
from collections.abc import Sequence
from 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
Expected output
{'P001': 'Wireless Earbuds', 'P006': 'Espresso Machine'}
25 22.9
Max reading: 22.9
Hint 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
ex_c13_generics.py
"""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]) == 25
assert Labeled("n", 5).value == 5
Output
{'P001': 'Wireless Earbuds', 'P006': 'Espresso Machine'}
25 22.9
Max reading: 22.9
Terminal
mypy --strict ex_c13_generics.py
Output
Success: no issues found in 1 source file

How it works:

  1. Each type parameter now lives in the brackets of the function or class that uses it. No module-level K, V, N or T remain to be reused by mistake.
  2. The bound [N: float] lets largest compare values with >: every float (and int) supports it. For largest([3, 25, 1]), N is int, so the result is an int, not just a float.
  3. class Labeled[T]: replaces the Generic[T] base class. Behavior and output are unchanged: the refactor touches only the declarations.
  4. Ruff’s UP046 and UP047 rules flag the old form. ruff check --fix --unsafe-fixes applies the rewrite. Ruff marks the fix unsafe because the new syntax infers variance, so review the result.

M12-X01 · Region summaries from nested JSON

Section titled “M12-X01 · Region summaries from nested JSON”
Challenge

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.

Expected output
Region Customers Orders Spend Top customer
East 6 10 2,900.85 Omar Farouk
North 7 18 5,097.14 Mateo Lopez
South 4 11 2,198.45 Ravi Patel
West 3 9 3,515.26 Mei Chen
ex_x01_regions.py (starter)
from pathlib import Path
from 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 table
Hint 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
ex_x01_regions.py
"""Summarize data/customers.json per region into typed records."""
from pathlib import Path
from 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()) == 20
assert sum(s["orders"] for s in summaries.values()) == 48
Output
Region Customers Orders Spend Top customer
East 6 10 2,900.85 Omar Farouk
North 7 18 5,097.14 Mateo Lopez
South 4 11 2,198.45 Ravi Patel
West 3 9 3,515.26 Mei Chen
Terminal
mypy --strict ex_x01_regions.py
Output
Success: no issues found in 1 source file

How it works:

  1. The input type (Customer) and the output type (RegionSummary) are both TypedDicts, so every key read and every key written is checked.
  2. Grouping first and summarizing second keeps each step simple. sorted(groups.items()) orders the regions alphabetically.
  3. max(members, key=spend) reuses the spend function as a key. It returns a Customer, so top["name"] is a checked str.
  4. 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”
Challenge

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.

Expected output
[37.8, 39.42]
[0.5, 1.0]
scale called 2 times
ex_x02_timed.py (starter)
import functools
import time
from 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
@timed
def 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 count
Hint 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
ex_x02_timed.py
"""A call-counting decorator that keeps the signature of the function."""
import functools
import time
from 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
@timed
def 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"] == 2
assert SECONDS["scale"] >= 0.0
Output
[37.8, 39.42]
[0.5, 1.0]
scale called 2 times

The check file, for mypy only:

ex_x02_check.py
"""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")
Terminal
mypy --strict ex_x02_timed.py
mypy ex_x02_check.py
Output
Success: no issues found in 1 source file
ex_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:

  1. P captures the parameter list of func (names, types, defaults) and R its return type. Callable[P, R] in the return hint says “the result has the same signature”.
  2. reveal_type(scale) shows the original signature after decoration, and the bad keyword argument is caught. With a naive hint such as Callable[..., Any], mypy would reveal a function that accepts anything and returns Any, and the bad call would pass.
  3. functools.wraps copies __name__ and the docstring at runtime; the hints copy the signature for the checker. You need both.
  4. try/finally records the call even when func raises. Timings go into SECONDS instead 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”
Challenge

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.

Expected output
C00001 72 84.69 False
Charges times tenure: 6,097.68
ex_x03_fields.py (starter)
from typing import Literal, overload
type Kind = Literal["int", "float", "bool"]
# TODO: three @overload signatures, one per kind
def 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 lines
Hint 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
ex_x03_fields.py
"""Parse CSV fields with a return type that follows the requested kind."""
from typing import Literal, overload
type Kind = Literal["int", "float", "bool"]
@overload
def parse_field(text: str, kind: Literal["int"]) -> int: ...
@overload
def parse_field(text: str, kind: Literal["float"]) -> float: ...
@overload
def 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)
Output
C00001 72 84.69 False
Charges times tenure: 6,097.68
ex_x03_check.py
"""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")
Terminal
mypy --strict ex_x03_fields.py
mypy ex_x03_check.py
Output
Success: no issues found in 1 source file
ex_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']) -> int
ex_x03_check.py:10: note: def parse_field(text: str, kind: Literal['float']) -> float
ex_x03_check.py:10: note: def parse_field(text: str, kind: Literal['bool']) -> bool
Found 1 error in 1 file (checked 1 source file)

How it works:

  1. The three overloads are only signatures. mypy picks the first one whose parameter types match the call, so "int" selects -> int.
  2. Because tenure is an int and charges a float, tenure * charges is checked as a float multiplication. Without overloads, both would be int | float | bool, and every use would need an isinstance check.
  3. The implementation is not visible to callers. It must accept every case the overloads describe; mypy checks that it is compatible with them.
  4. 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”
Challenge

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.

Expected output
linear MAE 154,798
per_sqft MAE 158,325
mean MAE 225,400
Best: linear
ex_x04_select.py (starter)
from collections.abc import Callable, Sequence
from 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, print
Hint 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
ex_x04_select.py
"""Pick the best of several models that follow the Regressor protocol."""
from collections.abc import Callable, Sequence
from 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)
Output
linear MAE 154,798
per_sqft MAE 158,325
mean MAE 225,400
Best: linear
Terminal
mypy --strict ex_x04_select.py
Output
Success: no issues found in 1 source file

How it works:

  1. LinearSqftRegressor matches Regressor by shape. Nothing in models.py had to change to accept it: this is the main benefit of a protocol.
  2. select_best depends only on the protocol and on the Metric alias, so any metric with the right signature (rmse, mape) can replace mae.
  3. The line fit gives the same MAE (154,798) as scikit-learn’s LinearRegression in the lesson, because both solve the same least-squares problem.
  4. min(scores, key=lambda name: scores[name]) avoids key=scores.get, which mypy rejects because get may return None.

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”
Challenge

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.

Expected output
30 products
Out of stock: ['P006', 'P019']
Beauty 3.86
Books 3.90
Clothing 3.76
Electronics 3.84
Home 3.82
Sports 3.94
ex_x05_pages.py (starter)
from collections.abc import Iterator
from pathlib import Path
from 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 lines
Hint 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
ex_x05_pages.py
"""Stream every product from the saved API pages by following `next`."""
from collections.abc import Iterator
from pathlib import Path
from 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}) == 30
assert page_file("https://api.example.com/v1/products?page=3&per_page=10").name == (
"products_page_3.json"
)
Output
30 products
Out of stock: ['P006', 'P019']
Beauty 3.86
Books 3.90
Clothing 3.76
Electronics 3.84
Home 3.82
Sports 3.94
Terminal
mypy --strict ex_x05_pages.py
Output
Success: no issues found in 1 source file

How it works:

  1. iter_products is a generator, so its return type is Iterator[Product] (module 10). yield from page["data"] yields each product of a page, and the caller sees one flat stream.
  2. path: Path | None needs its hint: it starts as a Path and becomes None at the end. The while path is not None condition narrows it inside the loop.
  3. next: str | None in ProductPage forces the None check before page_file. Forgetting it is a mypy error (Argument 1 to "page_file" has incompatible type "str | None"), not a crash on the last page.
  4. 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.