Skip to content

Part 3 checkpoint

This checkpoint tests Part 3 as a whole. Each exercise mixes two to four modules, as real design work does. You build small classes for data and ML objects, refactor procedural scripts into objects, repair a broken diamond of cooperative classes, make objects behave like built-ins, measure what __slots__ saves, write a context manager, choose between a dataclass, a NamedTuple, a TypedDict, an Enum, a plain class and composition, apply a pattern and decide when not to, and extend minilearn with a new transformer and a new estimator. The exercises use the course datasets in data/ and are new: they combine the skills in tasks that the module exercises and mini-projects do not ask.

The exercises test design judgment as well as syntax. Many solutions end with a short “why” section. Write your own reasons down before you read it.

How to use it:

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

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

Exercise Tier Type Modules
P3-01 Warm-up Predict the output 18, 19
P3-02 Warm-up Fix the bugs 20, 21
P3-03 Warm-up Write the code 18, 20
P3-04 Core Refactor procedural code to OOP 18, 20, 21
P3-05 Core Fix the bugs (a diamond, super(), MRO) 18, 19, 22
P3-06 Core Write the code (special methods) 18, 20
P3-07 Core Choose and justify 19, 21, 22
P3-08 Core Apply a pattern, and say when not to 19, 20, 22
P3-09 Core Extend minilearn: a transformer 19, 20, 22
P3-10 Core Write the code (Protocol, ABC, SOLID) 19, 20, 21, 22
P3-11 Core Interpret a measurement, then fix (__slots__) 18, 19, 21
P3-12 Core Fix the bug, then write a context manager 20, 21, 22
P3-13 Challenge Predict, then rewrite 19, 20, 21
P3-14 Challenge Interpret, then extend minilearn: an estimator 19, 21, 22
P3-15 Challenge Refactor procedural code to OOP 18, 20, 21, 22

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

The exercises use only the standard library, except P3-09 and P3-14. Those two import minilearn, the package of the module 22 project, exactly as the project’s reference solution writes it. If your own package differs, copy the 13 files of that reference solution into a minilearn/ folder, or adapt the imports. Run the two exercises in the folder that holds minilearn/, so that import minilearn finds it. They use these names:

  • from minilearn: BaseEstimator, TransformerMixin, RegressorMixin, ClassifierMixin, NotFittedError, check_is_fitted, register, make_model (with the registered name "mean"), Pipeline (with builder() and indexing by step name), StandardScaler, LinearRegression, KNNClassifier (its kneighbors() and the learned attributes distance_, X_train_, y_train_ and classes_), Distance, get_distance, Neighbor (fields index, distance, label) and train_test_split (which returns a Split with X_train, X_test, y_train and y_test);
  • the type aliases Rows from minilearn.base, and DistanceFunc and Row from minilearn.distances.

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

P3-01 · Predict the output: where Python finds an attribute

Section titled “P3-01 · Predict the output: where Python finds an attribute”
Warm-up

Predict the output: a temperature sensor class and a vibration subclass collect alerts, override a class attribute and each have a “private” limit. Write down every line that the script prints, in order, then run it.

Acceptance criteria:

  • Write your prediction for all 8 lines before you run the code.
  • Your prediction matches the Output in the solution, line by line.
  • For each line you got wrong, you can name the rule (instance namespace, class namespace, MRO or name mangling) that explains it.
Starter
class Sensor:
unit = "°C"
alerts: list[tuple[str, float]] = []
__limit = 40.0
def __init__(self, sensor_id: str) -> None:
self.sensor_id = sensor_id
self.readings: list[float] = []
def add(self, value: float) -> None:
self.readings.append(value)
if value > self.__limit:
self.alerts.append((self.sensor_id, value))
def describe(self) -> str:
return f"{self.sensor_id} [{self.unit}] limit {self.__limit}"
class VibrationSensor(Sensor):
unit = "mm/s"
__limit = 11.2
def __init__(self, sensor_id: str, axis: str) -> None:
super().__init__(sensor_id)
self.axis = axis
def describe(self) -> str:
return super().describe() + f", own limit {self.__limit}"
temp = Sensor("S1")
vib = VibrationSensor("S4", "x")
temp.add(44.89)
vib.add(18.98)
print(temp.describe())
print(vib.describe())
print(len(vib.readings), len(Sensor.alerts), vib.alerts is temp.alerts)
temp.unit = "°F"
print(temp.unit, Sensor.unit, vib.unit)
Sensor.unit = "K"
print(Sensor("S2").unit, temp.unit, vib.unit)
print(sorted(vars(vib)))
print([cls.__name__ for cls in VibrationSensor.__mro__])
print(hasattr(vib, "__limit"), hasattr(vib, "_VibrationSensor__limit"))
# TODO: write your prediction for each line before you run it
Hint 1

obj.name looks in vars(obj) first, then in the class, then along the MRO. An assignment obj.name = ... always writes into vars(obj). An in-place change such as self.alerts.append(...) writes nothing: it changes the object it finds.

Hint 2

Python renames self.__limit when it compiles a method, using the class where the method is written: inside Sensor.add() it becomes self._Sensor__limit. Which limit does vib.add(18.98) compare against?

Solution
class Sensor:
unit = "°C"
alerts: list[tuple[str, float]] = []
__limit = 40.0
def __init__(self, sensor_id: str) -> None:
self.sensor_id = sensor_id
self.readings: list[float] = []
def add(self, value: float) -> None:
self.readings.append(value)
if value > self.__limit:
self.alerts.append((self.sensor_id, value))
def describe(self) -> str:
return f"{self.sensor_id} [{self.unit}] limit {self.__limit}"
class VibrationSensor(Sensor):
unit = "mm/s"
__limit = 11.2
def __init__(self, sensor_id: str, axis: str) -> None:
super().__init__(sensor_id)
self.axis = axis
def describe(self) -> str:
return super().describe() + f", own limit {self.__limit}"
temp = Sensor("S1")
vib = VibrationSensor("S4", "x")
temp.add(44.89)
vib.add(18.98)
print(temp.describe())
print(vib.describe())
print(len(vib.readings), len(Sensor.alerts), vib.alerts is temp.alerts)
temp.unit = "°F"
print(temp.unit, Sensor.unit, vib.unit)
Sensor.unit = "K"
print(Sensor("S2").unit, temp.unit, vib.unit)
print(sorted(vars(vib)))
print([cls.__name__ for cls in VibrationSensor.__mro__])
print(hasattr(vib, "__limit"), hasattr(vib, "_VibrationSensor__limit"))
assert Sensor.alerts == [("S1", 44.89)] and Sensor.unit == "K"
Output
S1 [°C] limit 40.0
S4 [mm/s] limit 40.0, own limit 11.2
1 1 True
°F °C mm/s
K °F mm/s
['axis', 'readings', 'sensor_id']
['VibrationSensor', 'Sensor', 'object']
False True

How it works:

  1. describe() of the subclass calls super().describe(), which runs Sensor.describe(). There, self.unit finds "mm/s" on VibrationSensor, because the lookup starts at the object’s class. But self.__limit was renamed to self._Sensor__limit when Sensor was compiled, so it reads 40.0. Name mangling protects a name from subclasses: that is its job.
  2. For the same reason, vib.add(18.98) compares 18.98 with 40.0, not with 11.2, and adds no alert. The vibration limit of the subclass is invisible to the parent’s methods. To let subclasses change a limit, use a single underscore (_limit) or a plain class attribute.
  3. alerts is a class attribute, and append() changes the one shared list. So Sensor.alerts has 1 item, and vib.alerts is temp.alerts is True. Per-instance data such as readings belongs in __init__, as module 18 showed.
  4. temp.unit = "°F" creates an instance attribute that shadows the class attribute for temp only. Sensor.unit = "K" then changes the class: a new sensor sees "K", temp still sees its own "°F", and vib sees "mm/s" from its own class, which comes first in its MRO.
  5. vars(vib) holds only what __init__ assigned through self: axis, readings and sensor_id. The MRO of a single-inheritance class is the chain up to object.

P3-02 · Fix the bugs: distinct status events

Section titled “P3-02 · Fix the bugs: distinct status events”
Warm-up

Fix the bugs: the script should collect the distinct pairs (sensor, status) of data/sensors.csv in a set, list them sorted by sensor and then by severity, and print the worst status of each sensor. It crashes. The script has three bugs: two crashes and one wrong order. Fixing one bug can reveal the next. Keep Status an IntEnum, because the severity order matters.

Expected output
S1 OK
S1 WARN
S2 OK
S2 WARN
S2 FAIL
S3 OK
S3 WARN
S4 OK
S4 WARN
S4 FAIL
worst: S1 WARN, S2 FAIL, S3 WARN, S4 FAIL
Starter
import csv
from dataclasses import dataclass
from enum import IntEnum
class Status(IntEnum):
OK = 0
WARN = 1
FAIL = 2
@dataclass(order=True)
class StatusEvent:
status: Status
sensor_id: str
def __post_init__(self) -> None:
self.status = Status(self.status)
with open("data/sensors.csv", encoding="utf-8", newline="") as file:
rows = list(csv.DictReader(file))
events = {StatusEvent(row["status"], row["sensor_id"]) for row in rows}
for event in sorted(events):
print(event.sensor_id, event.status.name)
worst = {}
for event in sorted(events):
worst[event.sensor_id] = event.status
print("worst:", ", ".join(f"{s} {status.name}" for s, status in worst.items()))
Hint 1

The first error is ValueError: 'ok' is not a valid Status. Status(x) looks a member up by its value, and the values are 0, 1 and 2. How do you look a member up by its name?

Hint 2

What does a set need from its items, and when does a dataclass provide it? Once that is fixed, can __post_init__ still assign to a field, and where else could the text be converted? Which field does order=True compare first?

Solution
import csv
from dataclasses import dataclass
from enum import IntEnum
from typing import Self
class Status(IntEnum):
OK = 0
WARN = 1
FAIL = 2
@dataclass(frozen=True, order=True)
class StatusEvent:
sensor_id: str
status: Status
@classmethod
def from_row(cls, row: dict[str, str]) -> Self:
return cls(row["sensor_id"], Status[row["status"].upper()])
with open("data/sensors.csv", encoding="utf-8", newline="") as file:
events = {StatusEvent.from_row(row) for row in csv.DictReader(file)}
for event in sorted(events):
print(event.sensor_id, event.status.name)
worst = {}
for event in sorted(events):
worst[event.sensor_id] = event.status
print("worst:", ", ".join(f"{s} {status.name}" for s, status in worst.items()))
assert len(events) == 10
assert worst == {
"S1": Status.WARN,
"S2": Status.FAIL,
"S3": Status.WARN,
"S4": Status.FAIL,
}
assert Status.FAIL > Status.WARN > Status.OK
Output
S1 OK
S1 WARN
S2 OK
S2 WARN
S2 FAIL
S3 OK
S3 WARN
S4 OK
S4 WARN
S4 FAIL
worst: S1 WARN, S2 FAIL, S3 WARN, S4 FAIL

How it works:

  1. Bug 1: Status("ok") raises ValueError, because the values are integers. Status["OK"] looks up the member by name. The text of the file becomes the name with .upper().
  2. Bug 2: TypeError: unhashable type: 'StatusEvent'. A dataclass that defines __eq__ and is not frozen is unhashable, because a mutable object whose hash can change would get lost in a set. frozen=True adds a __hash__ built from the fields.
  3. The fix of bug 2 makes __post_init__ fail with FrozenInstanceError: cannot assign to field 'status'. The cleaner fix moves the conversion into the alternative constructor from_row(), so the object is created with the right type. (object.__setattr__(self, "status", ...) inside __post_init__ also works, but it hides the conversion in a back door.)
  4. Bug 3: order=True sorts by the first field first. With status first, the list came out by severity, then by sensor. Defining sensor_id first gives the required order. The worst status per sensor is then the last event of each sensor in sorted order, because IntEnum members compare as integers.
Warm-up

Write a class House for the rows of data/houses.csv, with:

  • __init__(house_id, sqft, price, condition, school_rating=None);
  • a class attribute CONDITIONS = range(1, 6) and a condition property whose setter raises ValueError outside that range, also in __init__;
  • a read-only property price_per_sqft;
  • a @staticmethod parse_optional_int(text) that returns None for a blank cell, and a @classmethod from_row(row) that uses it;
  • a __repr__ like the first line of the expected output.

Load all houses, then print the first house, the house with the highest price per square foot, the number of blank school ratings, the error for condition = 6 and the sorted instance attributes of one house.

Expected output
House('H0001', sqft=2420, price=1097500, condition=4, school_rating=10)
highest price per sqft: H0751 1,044.53
blank school ratings: 90
ValueError: condition must be 1 to 5, got 6
['_condition', 'house_id', 'price', 'school_rating', 'sqft']
Starter
import csv
from typing import Self
class House:
CONDITIONS = range(1, 6)
def __init__(self, house_id: str, sqft: int, price: int, condition: int,
school_rating: int | None = None) -> None:
... # TODO: store the values; let the property validate condition
# TODO: condition property and setter, price_per_sqft property
# TODO: parse_optional_int (static), from_row (class method), __repr__
with open("data/houses.csv", encoding="utf-8", newline="") as file:
houses = [House.from_row(row) for row in csv.DictReader(file)]
# TODO: print the five lines
Hint 1

Write self.condition = condition in __init__, not self._condition = condition. The assignment then runs the setter, so a wrong value fails as early as possible. The setter stores the value under _condition.

Hint 2

from_row is a class method because it builds a new object: it returns cls(...). parse_optional_int needs neither the class nor an instance, so it is static. max(houses, key=lambda h: h.price_per_sqft) finds the top house.

Solution
import csv
from typing import Self
class House:
"""One sale of data/houses.csv."""
CONDITIONS = range(1, 6) # class attribute: the same scale for every house
def __init__(
self,
house_id: str,
sqft: int,
price: int,
condition: int,
school_rating: int | None = None,
) -> None:
self.house_id = house_id
self.sqft = sqft
self.price = price
self.condition = condition # runs the setter, so __init__ validates too
self.school_rating = school_rating
@property
def condition(self) -> int:
return self._condition
@condition.setter
def condition(self, value: int) -> None:
if value not in self.CONDITIONS:
raise ValueError(f"condition must be 1 to 5, got {value}")
self._condition = value
@property
def price_per_sqft(self) -> float:
return self.price / self.sqft
@staticmethod
def parse_optional_int(text: str) -> int | None:
return int(text) if text.strip() else None
@classmethod
def from_row(cls, row: dict[str, str]) -> Self:
return cls(
row["house_id"],
int(row["sqft"]),
int(row["price"]),
int(row["condition"]),
cls.parse_optional_int(row["school_rating"]),
)
def __repr__(self) -> str:
return (
f"House({self.house_id!r}, sqft={self.sqft}, price={self.price}, "
f"condition={self.condition}, school_rating={self.school_rating})"
)
with open("data/houses.csv", encoding="utf-8", newline="") as file:
houses = [House.from_row(row) for row in csv.DictReader(file)]
print(houses[0])
top = max(houses, key=lambda house: house.price_per_sqft)
print(f"highest price per sqft: {top.house_id} {top.price_per_sqft:,.2f}")
print("blank school ratings:", sum(house.school_rating is None for house in houses))
try:
houses[0].condition = 6
except ValueError as error:
print("ValueError:", error)
print(sorted(vars(houses[0])))
assert len(houses) == 3000
assert houses[0].condition == 4
assert House.parse_optional_int(" ") is None
Output
House('H0001', sqft=2420, price=1097500, condition=4, school_rating=10)
highest price per sqft: H0751 1,044.53
blank school ratings: 90
ValueError: condition must be 1 to 5, got 6
['_condition', 'house_id', 'price', 'school_rating', 'sqft']

How it works:

  1. The setter runs on every assignment, including the one in __init__. So no House can exist with an invalid condition. The value lives in _condition, which is why vars() shows _condition and not condition.
  2. price_per_sqft is computed on access, so it can never disagree with price and sqft. A stored copy would go stale after a price correction.
  3. The top house, H0751, is one of the 8 injected price outliers that the data dictionary lists (Oak Hill, 1,370 sqft, 1,431,000). A ratio such as price per square foot makes outliers easy to find.
  4. The 90 blank school ratings match the data dictionary. parse_optional_int turns them into None, which is clearer than 0, a real-looking rating.

P3-04 · Refactor: an A/B test report as objects

Section titled “P3-04 · Refactor: an A/B test report as objects”
Core

Refactor procedural code into OOP: the starter summarizes the checkout test of data/ab_test.csv with three parallel dicts, then copies and edits the same loop for each device. Rewrite it with:

  • Variant, a StrEnum with CONTROL and TREATMENT;
  • GroupStats, a slotted dataclass with users, buyers and revenue, a method add(converted, revenue) and the properties conversion, revenue_per_user and aov (average order value of the buyers);
  • ABTest, built from rows, with from_csv(path), __getitem__(variant) (a Variant or its text), a lift property, a __repr__ and segment(column, value), which returns a new ABTest of the matching rows.

The first six lines must equal the output of the starter exactly. Then print the full test and the tablet segment.

Expected output
control users 5002 conversion 10.12% revenue/user 4.38 AOV 43.30
treatment users 4998 conversion 11.66% revenue/user 4.85 AOV 41.54
lift +15.3%
desktop control 12.01% treatment 14.47% lift +20.5%
mobile control 8.52% treatment 9.98% lift +17.1%
tablet control 12.52% treatment 11.38% lift -9.1%
ABTest(n_users=10000) ABTest(n_users=995)
Starter
import csv
with open("data/ab_test.csv", encoding="utf-8", newline="") as file:
rows = list(csv.DictReader(file))
users, buyers, revenue = {}, {}, {}
for row in rows:
g = row["group"]
users[g] = users.get(g, 0) + 1
buyers[g] = buyers.get(g, 0) + int(row["converted"])
revenue[g] = revenue.get(g, 0.0) + float(row["revenue"])
for g in sorted(users):
print(
f"{g:<9} users {users[g]:>5} conversion {buyers[g] / users[g]:.2%} "
f"revenue/user {revenue[g] / users[g]:.2f} AOV {revenue[g] / buyers[g]:.2f}"
)
lift = (buyers["treatment"] / users["treatment"]) / (
buyers["control"] / users["control"]
) - 1
print(f"lift {lift:+.1%}")
for device in ("desktop", "mobile", "tablet"):
du, db = {}, {}
for row in rows:
if row["device"] != device:
continue
g = row["group"]
du[g] = du.get(g, 0) + 1
db[g] = db.get(g, 0) + int(row["converted"])
c, t = db["control"] / du["control"], db["treatment"] / du["treatment"]
print(f"{device:<8} control {c:.2%} treatment {t:.2%} lift {t / c - 1:+.1%}")
# TODO: rewrite with Variant, GroupStats and ABTest; keep the output the same
Hint 1

Store the counts, not the rates. Rates are properties computed from the counts, so they are always consistent. self.buyers += converted works with a bool, because True counts as 1.

Hint 2

The device loop repeats the whole summary on a subset of rows. If ABTest can be built from any rows, segment() is one line: return type(self)(row for row in self.rows if row[column] == value). Then part.lift and part["control"].conversion replace the copied code.

Solution
import csv
from collections.abc import Iterable
from dataclasses import dataclass
from enum import StrEnum, auto
from typing import Self
class Variant(StrEnum):
CONTROL = auto()
TREATMENT = auto()
@dataclass(slots=True)
class GroupStats:
"""Running totals of one variant. The rates are computed, never stored."""
users: int = 0
buyers: int = 0
revenue: float = 0.0
def add(self, converted: bool, revenue: float) -> None:
self.users += 1
self.buyers += converted
self.revenue += revenue
@property
def conversion(self) -> float:
return self.buyers / self.users
@property
def revenue_per_user(self) -> float:
return self.revenue / self.users
@property
def aov(self) -> float: # average order value of the buyers
return self.revenue / self.buyers if self.buyers else 0.0
class ABTest:
"""The rows of an A/B test, with one GroupStats per variant."""
def __init__(self, rows: Iterable[dict[str, str]]) -> None:
self.rows = list(rows)
self.groups = {variant: GroupStats() for variant in Variant}
for row in self.rows:
stats = self.groups[Variant(row["group"])]
stats.add(row["converted"] == "1", float(row["revenue"]))
@classmethod
def from_csv(cls, path: str) -> Self:
with open(path, encoding="utf-8", newline="") as file:
return cls(csv.DictReader(file))
def __getitem__(self, variant: Variant | str) -> GroupStats:
return self.groups[Variant(variant)]
def __repr__(self) -> str:
return f"ABTest(n_users={len(self.rows)})"
@property
def lift(self) -> float:
return self["treatment"].conversion / self["control"].conversion - 1
def segment(self, column: str, value: str) -> Self:
"""A new ABTest with only the rows where row[column] == value."""
return type(self)(row for row in self.rows if row[column] == value)
test = ABTest.from_csv("data/ab_test.csv")
for variant in Variant:
s = test[variant]
print(
f"{variant:<9} users {s.users:>5} conversion {s.conversion:.2%} "
f"revenue/user {s.revenue_per_user:.2f} AOV {s.aov:.2f}"
)
print(f"lift {test.lift:+.1%}")
for device in ("desktop", "mobile", "tablet"):
part = test.segment("device", device)
c, t = part["control"].conversion, part["treatment"].conversion
print(f"{device:<8} control {c:.2%} treatment {t:.2%} lift {part.lift:+.1%}")
print(test, test.segment("device", "tablet"))
assert test["control"].users + test["treatment"].users == 10_000
assert round(test.lift, 3) == 0.153
Output
control users 5002 conversion 10.12% revenue/user 4.38 AOV 43.30
treatment users 4998 conversion 11.66% revenue/user 4.85 AOV 41.54
lift +15.3%
desktop control 12.01% treatment 14.47% lift +20.5%
mobile control 8.52% treatment 9.98% lift +17.1%
tablet control 12.52% treatment 11.38% lift -9.1%
ABTest(n_users=10000) ABTest(n_users=995)

How it works:

  1. Each class has one job. GroupStats keeps the totals of one variant and derives its rates. ABTest reads the rows, groups them, and answers questions about the test. The report code at the bottom only formats.
  2. segment() returns a new ABTest, so every question you can ask the whole test, you can ask a segment. The copied device loop disappears, and a segment by country costs no new code.
  3. Variant(row["group"]) rejects an unknown group name with a ValueError instead of creating a third dict key. Because a StrEnum member is a string, f"{variant:<9}" prints control, and test["control"] works as well as test[Variant.CONTROL].
  4. slots=True fits a small record with a fixed set of fields. GroupStats is mutable on purpose: add() updates it in place while the rows stream past.
  5. Interpret the result: the overall lift is +15.3%, but the tablet segment shows −9.1%. The tablet segment has only 995 users, about 60 buyers per variant, so its rate is noisy. Do not report a segment result without a test of significance (module 29).

P3-05 · Fix the bugs: a diamond of cleaning steps

Section titled “P3-05 · Fix the bugs: a diamond of cleaning steps”
Core

Fix the bugs: ClipStep (cap each value at high) and RoundStep (round to digits decimals) both inherit from the root class Step, which records each run. VibrationCleaner inherits from both, so the four classes form a diamond. Applied to the 143 vibration readings of sensor S4 on 2024-05-14, the cleaner should clip, then round, then record the run, with each class running exactly once.

First, predict the MRO of VibrationCleaner (the script prints it before anything can fail). Then fix the three bugs: a keyword argument that gets lost, a method that breaks the promise of Step.apply(), and an override that runs part of the chain twice. Do not change the job of any class.

Expected output
MRO: ['VibrationCleaner', 'ClipStep', 'RoundStep', 'Step', 'object']
143 readings; max before 13.27 after 11.2
capped: 9 | first 4: [6.6, 9.1, 10.0, 7.3]
history: ['clip', 'round', 'vibration']
Starter
import csv
from typing import Any
class Step:
"""The root of the chain: it records each run of apply() and ends the chain."""
def __init__(self, *, name: str) -> None:
self.name = name
self.history: list[str] = []
def apply(self, values: list[float]) -> list[float]:
self.history.append(self.name)
return values
class ClipStep(Step):
"""Cap every value at `high`."""
def __init__(self, *, high: float, name: str, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.high = high
def apply(self, values: list[float]) -> list[float]:
self.history.append("clip")
return super().apply([min(v, self.high) for v in values])
class RoundStep(Step):
"""Round every value to `digits` decimals."""
def __init__(self, *, digits: int, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.digits = digits
def apply(self, values: list[float]) -> list[float]:
self.history.append("round")
return super().apply(round(v, self.digits) for v in values)
class VibrationCleaner(ClipStep, RoundStep):
def __init__(self, high: float = 11.2, digits: int = 1) -> None:
super().__init__(name="vibration", high=high, digits=digits)
def apply(self, values: list[float]) -> list[float]:
values = ClipStep.apply(self, values) # make sure that both steps run
return RoundStep.apply(self, values)
with open("data/sensors.csv", encoding="utf-8", newline="") as file:
values = [
float(row["vibration_mm_s"])
for row in csv.DictReader(file)
if row["sensor_id"] == "S4"
and row["timestamp"].startswith("2024-05-14")
and row["vibration_mm_s"]
]
print("MRO:", [cls.__name__ for cls in VibrationCleaner.__mro__])
cleaner = VibrationCleaner()
cleaned = cleaner.apply(values)
print(len(cleaned), "readings; max before", max(values), "after", max(cleaned))
print("capped:", sum(v > cleaner.high for v in values), "| first 4:", cleaned[:4])
print("history:", cleaner.history)
Hint 1

The first error is TypeError: Step.__init__() missing 1 required keyword-only argument: 'name'. Follow name="vibration" along the MRO: which __init__ takes it out of **kwargs and never passes it on?

Hint 2

Step.apply() promises a list. What does RoundStep.apply() pass on? Then look at the history: each name should appear once. ClipStep.apply() already reaches RoundStep.apply() through super(), because RoundStep is next in the MRO of a VibrationCleaner. What does the override in VibrationCleaner add?

Solution
import csv
from typing import Any
class Step:
"""The root of the chain: it records each run of apply() and ends the chain."""
def __init__(self, *, name: str) -> None:
self.name = name
self.history: list[str] = []
def apply(self, values: list[float]) -> list[float]:
self.history.append(self.name)
return values
class ClipStep(Step):
"""Cap every value at `high`."""
def __init__(self, *, high: float, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.high = high
def apply(self, values: list[float]) -> list[float]:
self.history.append("clip")
return super().apply([min(v, self.high) for v in values])
class RoundStep(Step):
"""Round every value to `digits` decimals."""
def __init__(self, *, digits: int, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.digits = digits
def apply(self, values: list[float]) -> list[float]:
self.history.append("round")
return super().apply([round(v, self.digits) for v in values])
class VibrationCleaner(ClipStep, RoundStep):
def __init__(self, high: float = 11.2, digits: int = 1) -> None:
super().__init__(name="vibration", high=high, digits=digits)
with open("data/sensors.csv", encoding="utf-8", newline="") as file:
values = [
float(row["vibration_mm_s"])
for row in csv.DictReader(file)
if row["sensor_id"] == "S4"
and row["timestamp"].startswith("2024-05-14")
and row["vibration_mm_s"]
]
print("MRO:", [cls.__name__ for cls in VibrationCleaner.__mro__])
cleaner = VibrationCleaner()
cleaned = cleaner.apply(values)
print(len(cleaned), "readings; max before", max(values), "after", max(cleaned))
print("capped:", sum(v > cleaner.high for v in values), "| first 4:", cleaned[:4])
print("history:", cleaner.history)
assert cleaner.history == ["clip", "round", "vibration"]
assert max(cleaned) == 11.2 and all(v == round(v, 1) for v in cleaned)
assert len(cleaned) == len(values) == 143
Output
MRO: ['VibrationCleaner', 'ClipStep', 'RoundStep', 'Step', 'object']
143 readings; max before 13.27 after 11.2
capped: 9 | first 4: [6.6, 9.1, 10.0, 7.3]
history: ['clip', 'round', 'vibration']

How it works:

  1. The MRO is VibrationCleaner, ClipStep, RoundStep, Step, object. C3 puts Step after both of its children, so the shared root runs last and once. Inside a VibrationCleaner, super() in ClipStep means RoundStep, not Step: super() follows the MRO of the object, not the parents written in the class line.
  2. Bug 1: ClipStep.__init__ declared name as its own parameter, so name left **kwargs and never reached Step.__init__. A cooperative __init__ takes only the arguments it uses and passes on all the others.
  3. Bug 2: RoundStep.apply() passed a generator expression down the chain, so apply() returned a generator and len(cleaned) failed with TypeError: object of type 'generator' has no len(). Every override must keep the promise of the parent’s signature, here “returns a list” (the Liskov rule of module 22). mypy reports this bug before you run the code, because the hint says list[float].
  4. Bug 3: the override called ClipStep.apply(self, ...) and then RoundStep.apply(self, ...) by name. The first call already ran the whole chain (clip, round, vibration), so the second ran round and vibration again, and the history had five entries. Nothing crashed, which makes this the dangerous bug: a step that is not idempotent, such as a unit conversion, would be applied twice. Delete the override: super() already reaches every class once.
  5. Because both steps inherit from Step, self.history and super().apply() are declared for them, and mypy can check every call. Mixins that do not inherit from the root need class-level annotations for what they expect from their host, as in P3-14.

P3-06 · A daily revenue series that behaves like a built-in

Section titled “P3-06 · A daily revenue series that behaves like a built-in”
Core

Write a class DailySeries that holds one float per date ("YYYY-MM-DD"), in date order, and a name. Give it:

  • from_rows(rows, value, name), a class method that sums the column value per order_date;
  • __repr__, __len__, __iter__ (over the dates, like a dict), __contains__ and a total property;
  • __getitem__ with a date (a day without sales gives 0.0) and with a slice of dates such as ["2024-11-01":"2024-11-30"] (both ends included), which returns a DailySeries;
  • + and / between two series, aligned by date over the union of their dates, and __radd__, so that sum() works. Any other operand must give Python’s own TypeError.

Build one series per category of data/sales.csv. Add them with sum(), look up Black Friday 2024, slice November 2024, and find the day when Electronics had its largest share of the revenue.

Expected output
DailySeries('Beauty', 702 days, total=150,417.76)
DailySeries('Books', 689 days, total=106,908.12)
DailySeries('Beauty+Books+Clothing+Electronics+Home+Sports', 731 days, total=3,596,523.83)
True 33,619.18
DailySeries('total', 30 days, total=268,466.55)
Electronics share: 50.3%, peak 2023-07-16 89.9%
TypeError: unsupported operand type(s) for +: 'DailySeries' and 'int'
Starter
import csv
class DailySeries:
def __init__(self, values: dict[str, float], name: str = "") -> None:
self.values = dict(sorted(values.items()))
self.name = name
# TODO: from_rows, __repr__, __len__, __iter__, __contains__, total
# TODO: __getitem__ for a date and for a slice of dates
# TODO: __add__, __radd__ and __truediv__
with open("data/sales.csv", encoding="utf-8", newline="") as file:
rows = list(csv.DictReader(file))
categories = sorted({row["category"] for row in rows})
# TODO: one series per category, sum() them, then the other lines
Hint 1

sum(series_list) computes 0 + first first. int.__add__ does not know your class and returns NotImplemented, so Python calls first.__radd__(0). Return self for 0, and NotImplemented for anything else.

Hint 2

+ and / differ only in the operation. Write one helper _combine(other, op, name) that returns NotImplemented when other is not a DailySeries, and otherwise builds {day: op(self[day], other[day]) for day in self.values.keys() | other.values.keys()}. math.fsum gives the correctly rounded total. Since Python 3.12, sum() of floats is compensated too, but fsum states the intent. Build new series with type(self)(...), so that a subclass gets its own class back.

Solution
import csv
import math
from collections.abc import Callable, Iterator
from typing import Self
class DailySeries:
"""One float per date ("YYYY-MM-DD"), kept in date order."""
def __init__(self, values: dict[str, float], name: str = "") -> None:
self.values = dict(sorted(values.items()))
self.name = name
@classmethod
def from_rows(cls, rows: list[dict[str, str]], value: str, name: str = "") -> Self:
totals: dict[str, float] = {}
for row in rows:
day = row["order_date"]
totals[day] = totals.get(day, 0.0) + float(row[value])
return cls(totals, name)
def __repr__(self) -> str:
return f"DailySeries({self.name!r}, {len(self)} days, total={self.total:,.2f})"
def __len__(self) -> int:
return len(self.values)
def __iter__(self) -> Iterator[str]:
return iter(self.values) # like a dict: iterate over the keys (dates)
def __contains__(self, day: object) -> bool:
return day in self.values
def __getitem__(self, key: str | slice) -> float | Self:
if isinstance(key, slice): # date range, both ends included
start, stop = key.start or "", key.stop or "9999"
part = {d: v for d, v in self.values.items() if start <= d <= stop}
return type(self)(part, self.name)
return self.values.get(key, 0.0) # a day without sales sold nothing
@property
def total(self) -> float:
return math.fsum(self.values.values())
def _combine(
self, other: object, op: Callable[[float, float], float], name: str
) -> Self:
if not isinstance(other, DailySeries):
return NotImplemented
days = self.values.keys() | other.values.keys()
return type(self)({d: op(self[d], other[d]) for d in days}, name)
def __add__(self, other: object) -> Self:
name = f"{self.name}+{other.name}" if isinstance(other, DailySeries) else ""
return self._combine(other, lambda a, b: a + b, name)
def __radd__(self, other: object) -> Self:
if other == 0: # sum() starts with 0
return self
return NotImplemented
def __truediv__(self, other: object) -> Self:
name = f"{self.name}/{other.name}" if isinstance(other, DailySeries) else ""
return self._combine(other, lambda a, b: a / b if b else 0.0, name)
with open("data/sales.csv", encoding="utf-8", newline="") as file:
rows = list(csv.DictReader(file))
categories = sorted({row["category"] for row in rows})
by_category = [
DailySeries.from_rows([r for r in rows if r["category"] == c], "revenue", c)
for c in categories
]
for series in by_category[:2]:
print(series)
total = sum(by_category)
print(total)
total.name = "total"
print("2024-11-29" in total, f"{total['2024-11-29']:,.2f}")
print(total["2024-11-01":"2024-11-30"])
electronics = by_category[categories.index("Electronics")]
share = electronics / total
peak = max(share, key=share.__getitem__)
overall = electronics.total / total.total
print(f"Electronics share: {overall:.1%}, peak {peak} {share[peak]:.1%}")
try:
print(total + 100)
except TypeError as error:
print("TypeError:", error)
assert abs(total.total - 3_596_523.83) < 0.01
assert len(total) == 731 and "2023-12-25" in total
assert abs(total["2024-11-29"] - 33_619.18) < 0.01
Output
DailySeries('Beauty', 702 days, total=150,417.76)
DailySeries('Books', 689 days, total=106,908.12)
DailySeries('Beauty+Books+Clothing+Electronics+Home+Sports', 731 days, total=3,596,523.83)
True 33,619.18
DailySeries('total', 30 days, total=268,466.55)
Electronics share: 50.3%, peak 2023-07-16 89.9%
TypeError: unsupported operand type(s) for +: 'DailySeries' and 'int'

How it works:

  1. sum() calls __radd__(0) once, then __add__ five times. The name shows the chain. The total, 3,596,523.83, and Black Friday 2024, 33,619.18, match the data dictionary. So does November 2024 (268,467 rounded).
  2. Each category has fewer than 731 days (Books has 689), because some days had no sale in that category. The union of dates in _combine() and the 0.0 for a missing day align the series. With the intersection, sum() would silently drop every day that one category missed.
  3. in uses __contains__ (a dict lookup), and max(share, key=share.__getitem__) works because __iter__ yields the dates. The slice and the operators build the result with type(self)(...), so they return the same class, as built-in sequences do, also for a subclass.
  4. total + 100 raises Python’s own TypeError, because both __add__ and int.__radd__ returned NotImplemented. Raising your own error inside __add__ would block a reflected method that another class might offer.
  5. Interpret the result: Electronics brings 50.3% of the revenue, and on 2023-07-16 it brought 89.9%. One day’s share depends on a few expensive orders, as the data dictionary warns. For a trend, compare weekly or monthly shares.

P3-07 · Choose and justify: eight design decisions

Section titled “P3-07 · Choose and justify: eight design decisions”
Core

Choose a design and justify it: for each job, name the construct you would use (a dataclass with options, NamedTuple, TypedDict, an Enum kind, a plain class, a function, composition or a pattern) and give one sentence of reason. Then implement jobs 1, 2, 3 and 8 on the course data.

  1. The device column of data/ab_test.csv: three fixed values that are read from and written back to CSV files.
  2. The key of a dict that holds the maximum temperature of each sensor on each day of data/sensors.csv. Callers unpack the key as for (sensor_id, day), temp in ....
  3. The model section of data/config.json (type, target, test size, random state): read once, passed to many functions, never changed, and written back to JSON after a change. A test size outside (0, 1) must fail at once.
  4. Per-sensor tallies (counts of ok, warn and fail, the last status) that a loop updates 8,064 times.
  5. A KNN churn model with fit(), predict() and learned attributes.
  6. A model that scales the features, then classifies. A colleague proposes class ScaledKNN(StandardScaler, KNNClassifier).
  7. A gradient-descent fit() must show the loss of each epoch live in a terminal, write it to a log file in production, and stay silent in tests.
  8. The product records of data/api/products_page_1.json, which the code reads and passes unchanged to typed functions.

For job 2, print the number of sensor-days, the 3 hottest and the value for S4 on 2024-05-14. For job 3, show that assignment fails, that replace() makes a changed copy that asdict() turns into JSON, and that replace() validates too. For job 8, compute the stock value (price × stock) of the products in stock on page 1.

Expected output
desktop 3428 users conversion 13.24%
mobile 5577 users conversion 9.25%
tablet 995 users conversion 11.96%
56 sensor-days
S2 2024-05-02 max 44.89 °C
S4 2024-05-03 max 44.36 °C
S3 2024-05-08 max 41.66 °C
S4 on May 14: 28.51
ModelConfig(type='logistic_regression', target='churned', test_size=0.25, random_state=42)
FrozenInstanceError: cannot assign to field 'test_size'
{"type": "logistic_regression", "target": "churned", "test_size": 0.2, "random_state": 42}
ValueError: test_size must be in (0, 1), got 1.5
page 1: 10 products, stock value 205,173.60 USD
Starter
import csv
import json
# TODO: write your choice and one reason for each of the 8 jobs as comments
# TODO: job 1: an enum for the devices; print the conversion per device
# TODO: job 2: a key type for (sensor, day); the daily maximum temperatures
# TODO: job 3: a config record loaded from data/config.json, with validation
# TODO: job 8: types for the API records; the stock value of page 1
Hint 1

Ask two questions for each job. Does it have behavior, or is it only data? Must it change after it is created? Then ask what the callers do with it: unpack it, use it as a dict key, compare it with text, send it to JSON.

Hint 2

A dict key must be hashable. replace() calls __init__ again, so __post_init__ checks the copy too. For job 6, ask whether a scaled model is a scaler. For job 7, count the listeners and ask when they need the values. For job 8, ask whether the code creates the records or only receives them.

Solution
import csv
import json
from dataclasses import FrozenInstanceError, asdict, dataclass, replace
from enum import StrEnum
from typing import NamedTuple, Self, TypedDict
# Job 1: the device column of ab_test.csv: fixed choices that are also text.
class Device(StrEnum):
DESKTOP = "desktop"
MOBILE = "mobile"
TABLET = "tablet"
# Job 2: a small immutable key for a dict of (sensor, day) aggregates.
class SensorDay(NamedTuple):
sensor_id: str
day: str
# Job 3: the model settings of config.json: read once, shared, never changed.
@dataclass(frozen=True, slots=True)
class ModelConfig:
type: str
target: str
test_size: float
random_state: int
def __post_init__(self) -> None:
if not 0 < self.test_size < 1:
raise ValueError(f"test_size must be in (0, 1), got {self.test_size}")
@classmethod
def from_json(cls, path: str) -> Self:
with open(path, encoding="utf-8") as file:
section = json.load(file)["model"]
return cls(**{k: v for k, v in section.items() if k != "params"})
# Job 8: API records that the code reads and passes on unchanged.
class Price(TypedDict):
amount: float
currency: str
class ApiProduct(TypedDict):
id: str
name: str
price: Price
in_stock: bool
stock: int
def stock_value(products: list[ApiProduct]) -> float:
return sum(p["price"]["amount"] * p["stock"] for p in products if p["in_stock"])
with open("data/ab_test.csv", encoding="utf-8", newline="") as file:
users = list(csv.DictReader(file))
for device in Device:
group = [u for u in users if u["device"] == device] # a StrEnum equals its text
rate = sum(u["converted"] == "1" for u in group) / len(group)
print(f"{device:<8} {len(group):>5} users conversion {rate:.2%}")
hottest: dict[SensorDay, float] = {}
with open("data/sensors.csv", encoding="utf-8", newline="") as file:
for row in csv.DictReader(file):
if row["temperature_c"]:
key = SensorDay(row["sensor_id"], row["timestamp"][:10])
hottest[key] = max(hottest.get(key, -273.15), float(row["temperature_c"]))
print(len(hottest), "sensor-days")
for (sensor_id, day), temp in sorted(hottest.items(), key=lambda kv: -kv[1])[:3]:
print(f" {sensor_id} {day} max {temp} °C") # a NamedTuple unpacks like a tuple
print(" S4 on May 14:", hottest[SensorDay("S4", "2024-05-14")])
config = ModelConfig.from_json("data/config.json")
print(config)
try:
config.test_size = 0.5 # type: ignore[misc]
except FrozenInstanceError as error:
print("FrozenInstanceError:", error)
smaller = replace(config, test_size=0.2)
print(json.dumps(asdict(smaller)))
try:
replace(config, test_size=1.5)
except ValueError as error:
print("ValueError:", error)
with open("data/api/products_page_1.json", encoding="utf-8") as file:
page: list[ApiProduct] = json.load(file)["data"]
print(f"page 1: {len(page)} products, stock value {stock_value(page):,.2f} USD")
assert Device("tablet") is Device.TABLET
assert hottest[("S4", "2024-05-14")] == hottest[SensorDay("S4", "2024-05-14")]
assert config.test_size == 0.25 and smaller.test_size == 0.2
Output
desktop 3428 users conversion 13.24%
mobile 5577 users conversion 9.25%
tablet 995 users conversion 11.96%
56 sensor-days
S2 2024-05-02 max 44.89 °C
S4 2024-05-03 max 44.36 °C
S3 2024-05-08 max 41.66 °C
S4 on May 14: 28.51
ModelConfig(type='logistic_regression', target='churned', test_size=0.25, random_state=42)
FrozenInstanceError: cannot assign to field 'test_size'
{"type": "logistic_regression", "target": "churned", "test_size": 0.2, "random_state": 42}
ValueError: test_size must be in (0, 1), got 1.5
page 1: 10 products, stock value 205,173.60 USD
Job Choice Reason
1 StrEnum A fixed set of choices whose members are also the text of the file, so they compare equal to the CSV cells and write back unchanged.
2 NamedTuple A hashable, immutable key that unpacks like a tuple, and it equals the plain tuple ("S4", "2024-05-14"), so old code that uses tuples keeps working.
3 @dataclass(frozen=True, slots=True) with __post_init__ Read-only after creation, so it is safe to share; __post_init__ rejects a bad test size at once, also in replace(); asdict() gives a dict for json.dumps.
4 @dataclass(slots=True) (mutable), or a Counter per sensor The values change in place on every row; slots fixes the field names and saves memory. A frozen record would force a new object per row.
5 A plain class on BaseEstimator Its main content is behavior and the learned state that fit() creates, not a record of fields. The base class already gives the parameters, the repr and equality, so @dataclass adds nothing and would replace those methods with its own versions.
6 Composition: Pipeline([("scale", StandardScaler()), ("knn", KNNClassifier())]) A scaled model has a scaler; it is not a scaler. With multiple inheritance only one _fit() hook would run (the first in the MRO), so the KNN part would never be trained, and both classes’ parameters would have to share one __init__.
7 Observer: fit() calls the on_epoch_end() of the callbacks it receives There are several listeners (terminal, log file, none), and they need each value while training runs. Returning the list of losses at the end is not live, and a print() inside fit() is hard-wired and cannot be silenced in tests.
8 TypedDict The records already exist as dicts from json.load. A TypedDict adds type checking without converting anything. A dataclass would need a conversion step, and a pydantic model pays off only when the input is untrusted and must be validated.

How it works:

  1. for device in Device iterates in definition order. u["device"] == device compares a string with a StrEnum member, which is a string, so no conversion is needed. The rates match the data dictionary: desktop 13.24%, tablet 11.96%, mobile 9.25%.
  2. The SensorDay key is hashable because a NamedTuple is a tuple. The final assert shows the tuple behavior that helps here: a plain tuple finds the same dict entry. The 3 hottest values lie far above the daily cycle of each sensor. The data dictionary lists 40 temperature spikes, so treat these maxima as candidates for review, not as real heat.
  3. The frozen dataclass rejects config.test_size = 0.5 with FrozenInstanceError. replace() builds a new object through __init__, so __post_init__ rejects 1.5 there too, and the original keeps 0.25. asdict() converts the copy recursively to plain dicts for JSON.
  4. The TypedDict classes cost nothing at run time: page is the list that json.load returned. mypy now checks p["price"]["amount"] and would report a typo such as p["prices"].

P3-08 · Fill sensor gaps with interchangeable strategies

Section titled “P3-08 · Fill sensor gaps with interchangeable strategies”
Core

Apply the strategy pattern: sensor S3 of data/sensors.csv has 6 blank temperatures. Write four fill strategies for a column of float | None: fill_previous (carry the last reading forward), fill_linear (a straight line between the readings on both sides), fill_mean (the column mean) and FillConstant(value), a callable object with a setting. Describe them with a Filler Protocol, map names to them in a dict, and write fill(values, strategy="previous"), which accepts a name or any Filler. An unknown name raises ValueError with the known names. Print what each strategy puts in the first gap and the column mean after filling.

Then answer in a comment: when would you not build this?

Expected output
S3: 2016 readings, 6 blank, first at 2024-05-03T23:40:00
around it: 20.85 None 20.82
previous fills 20.85 column mean 23.528
linear fills 20.84 column mean 23.528
mean fills 23.53 column mean 23.529
zero fills 0.00 column mean 23.459
custom 22.0 FillConstant(0.0)
ValueError: unknown strategy 'median'; use previous, linear, mean, zero
Starter
import csv
import statistics
from collections.abc import Sequence
from typing import Protocol
type Column = Sequence[float | None]
# TODO: a Filler Protocol with __call__(self, values: Column) -> list[float]
# TODO: fill_previous, fill_linear, fill_mean and the class FillConstant
# TODO: FILLERS, a dict: "previous", "linear", "mean", "zero" -> FillConstant(0.0)
# TODO: fill(values, strategy="previous")
with open("data/sensors.csv", encoding="utf-8", newline="") as file:
s3 = [row for row in csv.DictReader(file) if row["sensor_id"] == "S3"]
temps = [float(r["temperature_c"]) if r["temperature_c"] else None for r in s3]
# TODO: print the lines of the expected output
Hint 1

A Protocol with only __call__ matches every function with the same signature, and every object whose class defines that __call__. So plain functions and FillConstant(0.0) fit the same dict without a common base class.

Hint 2

For fill_linear, collect the indexes of the known values. For a gap at index i, take the nearest known index on the left and on the right, and interpolate: a + (b - a) * (i - left) / (right - left). A gap at the start or the end takes the nearest reading. In fill(), look the name up with try/except KeyError and raise a ValueError from None.

Solution
import csv
import statistics
from collections.abc import Sequence
from typing import Protocol
type Column = Sequence[float | None]
class Filler(Protocol):
"""Any callable that replaces the blanks (None) of a column."""
def __call__(self, values: Column) -> list[float]: ...
def fill_previous(values: Column) -> list[float]:
"""Carry the last reading forward; a leading blank takes the first reading."""
first = next(v for v in values if v is not None)
filled, last = [], first
for v in values:
last = last if v is None else v
filled.append(last)
return filled
def fill_linear(values: Column) -> list[float]:
"""Draw a straight line between the readings on both sides of each gap."""
known = [i for i, v in enumerate(values) if v is not None]
filled = []
for i, v in enumerate(values):
if v is not None:
filled.append(v)
continue
left = max((k for k in known if k < i), default=None)
right = min((k for k in known if k > i), default=None)
if left is None or right is None: # a gap at an edge: nearest reading
filled.append(values[right if left is None else left])
else:
a, b = values[left], values[right]
filled.append(a + (b - a) * (i - left) / (right - left))
return filled
def fill_mean(values: Column) -> list[float]:
mean = statistics.fmean(v for v in values if v is not None)
return [mean if v is None else v for v in values]
class FillConstant:
"""A strategy with a setting: a callable object, not a subclass."""
def __init__(self, value: float) -> None:
self.value = value
def __call__(self, values: Column) -> list[float]:
return [self.value if v is None else v for v in values]
def __repr__(self) -> str:
return f"FillConstant({self.value})"
FILLERS: dict[str, Filler] = {
"previous": fill_previous,
"linear": fill_linear,
"mean": fill_mean,
"zero": FillConstant(0.0),
}
def fill(values: Column, strategy: str | Filler = "previous") -> list[float]:
"""Fill the blanks with a named strategy or with any Filler."""
if isinstance(strategy, str):
try:
strategy = FILLERS[strategy]
except KeyError:
known = ", ".join(FILLERS)
raise ValueError(f"unknown strategy {strategy!r}; use {known}") from None
return strategy(values)
with open("data/sensors.csv", encoding="utf-8", newline="") as file:
s3 = [row for row in csv.DictReader(file) if row["sensor_id"] == "S3"]
temps = [float(r["temperature_c"]) if r["temperature_c"] else None for r in s3]
gap = temps.index(None)
first_blank = s3[gap]["timestamp"]
print(f"S3: {len(temps)} readings, {temps.count(None)} blank, first at {first_blank}")
print(f" around it: {temps[gap - 1]} None {temps[gap + 1]}")
for name in FILLERS:
filled = fill(temps, name)
mean = statistics.fmean(filled)
print(f" {name:<9} fills {filled[gap]:6.2f} column mean {mean:.3f}")
print(" custom ", fill(temps, FillConstant(22.0))[gap], FILLERS["zero"])
try:
fill(temps, "median")
except ValueError as error:
print("ValueError:", error)
assert all(v is not None for v in fill(temps, "linear"))
assert fill([None, 2.0, None, 4.0, None], fill_linear) == [2.0, 2.0, 3.0, 4.0, 4.0]
assert fill([None, 2.0, None], "previous") == [2.0, 2.0, 2.0]
Output
S3: 2016 readings, 6 blank, first at 2024-05-03T23:40:00
around it: 20.85 None 20.82
previous fills 20.85 column mean 23.528
linear fills 20.84 column mean 23.528
mean fills 23.53 column mean 23.529
zero fills 0.00 column mean 23.459
custom 22.0 FillConstant(0.0)
ValueError: unknown strategy 'median'; use previous, linear, mean, zero

How it works:

  1. fill() depends on the Filler Protocol, not on any concrete strategy. A new strategy is a new function and one dict entry, and fill() does not change (open/closed). A caller can also pass its own FillConstant(22.0) without registering it.
  2. FillConstant is a class only because it has a setting. The other strategies keep no state between calls, so they are functions. Its __repr__ makes the registry readable when you print it.
  3. Interpret the result: the first gap is at 23:40, between 20.85 and 20.82. previous and linear fill about 20.8. mean fills 23.53, almost 3 °C too warm, because the column mean ignores the daily cycle (night is cold). zero is wrong by 20 °C and pulls the column mean down from 23.528 to 23.459. Six gaps in 2,016 readings barely move the mean, but each bad value is a false spike for an anomaly detector.
  4. When not to build it: if a script only ever fills with the previous value, call fill_previous(temps) directly. The Protocol, the dict and fill() pay off when a config file or a user chooses the strategy by name, or when you compare strategies, as here. Add the structure when that need appears (YAGNI, module 22).

P3-09 · Extend minilearn: a quantile clipper

Section titled “P3-09 · Extend minilearn: a quantile clipper”
Core

Extend minilearn: write a transformer QuantileClipper(lower=0.01, upper=0.99) that learns the lower and upper quantile of each feature in fit() and caps every value to that range in transform(). It must follow the conventions of your package:

  • it inherits TransformerMixin and BaseEstimator and writes only the hooks _fit() and _transform();
  • the constructor stores its arguments unchanged; _fit() checks 0 <= lower < upper <= 1 and sets the learned attributes low_ and high_;
  • it registers itself as "clipper", so that make_model("clipper", upper=0.95) builds it.

Use linear interpolation for the quantile (position q * (n - 1) in the sorted values), as NumPy does by default. Then split sqft → price of data/houses.csv with train_test_split(test_size=0.25, random_state=42) Choose between three pipelines built with Pipeline.builder(): the clipper with upper 1.0, 0.99 and 0.95 (and lower=0.0), followed by LinearRegression. Compare them on a validation split of the training part (train_test_split(split.X_train, split.y_train, test_size=0.25, random_state=0)), refit the kept setting on the whole training part, and score it on the test part once. Run it in the folder that holds minilearn/ (see Setup).

Expected output
QuantileClipper(lower=0.01, upper=0.95) {'lower': 0.01, 'upper': 0.95}
NotFittedError: QuantileClipper is not fitted yet; call fit() first
learned low_=[700.0], high_=[3200.0]
capped training rows: 134 of 2250
upper=1.0 high_= 5690 validation R² 0.487
upper=0.99 high_= 4161 validation R² 0.439
upper=0.95 high_= 3220 validation R² 0.398
kept upper=1.0: test R² 0.545
ValueError: need 0 <= lower < upper <= 1, got 0.9 and 0.1
Starter
import csv
from minilearn import (
BaseEstimator,
LinearRegression,
NotFittedError,
Pipeline,
TransformerMixin,
make_model,
register,
train_test_split,
)
from minilearn.base import Rows
def quantile(sorted_values: list[float], q: float) -> float:
... # TODO: linear interpolation at position q * (n - 1)
# TODO: @register("clipper") class QuantileClipper(TransformerMixin, BaseEstimator)
# TODO: load the houses, split, show the conventions, compare the three pipelines
Hint 1

Do not write fit() or transform(): the template methods of BaseEstimator and TransformerMixin already validate the rows, set n_features_in_, raise NotFittedError and call your hooks. fit_transform() comes from the mixin too.

Hint 2

columns = [sorted(col) for col in zip(*X, strict=True)] gives each feature sorted. Clip with min(max(v, lo), hi). The rows of a Split are tuples and your output rows are lists: compare list(a) != b when you count the capped rows.

Solution
import csv
import math
from minilearn import (
BaseEstimator,
LinearRegression,
NotFittedError,
Pipeline,
TransformerMixin,
make_model,
register,
train_test_split,
)
from minilearn.base import Rows
def quantile(sorted_values: list[float], q: float) -> float:
"""Linear interpolation between the two nearest ranks (NumPy's default)."""
position = q * (len(sorted_values) - 1)
low, high = math.floor(position), math.ceil(position)
weight = position - low
return sorted_values[low] * (1 - weight) + sorted_values[high] * weight
@register("clipper")
class QuantileClipper(TransformerMixin, BaseEstimator):
"""Cap each feature at the quantiles `lower` and `upper` seen in fit()."""
def __init__(self, lower: float = 0.01, upper: float = 0.99) -> None:
self.lower = lower # stored unchanged; checked in _fit()
self.upper = upper
def _fit(self, X: Rows, y: object = None) -> None:
if not 0 <= self.lower < self.upper <= 1:
raise ValueError(
f"need 0 <= lower < upper <= 1, got {self.lower} and {self.upper}"
)
columns = [sorted(col) for col in zip(*X, strict=True)]
self.low_ = [quantile(col, self.lower) for col in columns]
self.high_ = [quantile(col, self.upper) for col in columns]
def _transform(self, X: Rows) -> Rows:
bounds = list(zip(self.low_, self.high_, strict=True))
return [
[min(max(v, lo), hi) for v, (lo, hi) in zip(row, bounds, strict=True)]
for row in X
]
with open("data/houses.csv", encoding="utf-8", newline="") as file:
houses = list(csv.DictReader(file))
X = [[float(h["sqft"])] for h in houses]
y = [float(h["price"]) for h in houses]
split = train_test_split(X, y, test_size=0.25, random_state=42)
clipper = make_model("clipper", upper=0.95)
print(clipper, clipper.get_params())
try:
clipper.transform(split.X_test)
except NotFittedError as error:
print("NotFittedError:", error)
clipped = clipper.fit_transform(split.X_train)
print(f"learned low_={clipper.low_}, high_={clipper.high_}")
pairs = zip(split.X_train, clipped, strict=True)
print("capped training rows:", sum(list(a) != b for a, b in pairs), "of", len(clipped))
inner = train_test_split(split.X_train, split.y_train, test_size=0.25, random_state=0)
def clip_line(upper: float) -> Pipeline:
return (
Pipeline.builder()
.add("clip", QuantileClipper(lower=0.0, upper=upper))
.add("line", LinearRegression())
.build()
)
scores = {}
for upper in (1.0, 0.99, 0.95):
pipe = clip_line(upper).fit(inner.X_train, inner.y_train)
scores[upper] = pipe.score(inner.X_test, inner.y_test)
high = pipe["clip"].high_[0]
print(f"upper={upper:<4} high_={high:>6.0f} validation R² {scores[upper]:.3f}")
best = max(scores, key=scores.__getitem__)
final = clip_line(best).fit(split.X_train, split.y_train)
print(f"kept upper={best}: test R² {final.score(split.X_test, split.y_test):.3f}")
try:
QuantileClipper(lower=0.9, upper=0.1).fit(split.X_train)
except ValueError as error:
print("ValueError:", error)
assert isinstance(make_model("clipper"), QuantileClipper)
assert quantile([1.0, 2.0, 3.0, 4.0], 0.5) == 2.5
assert clipper.fit(split.X_train) is clipper
assert best == max(scores, key=scores.get)
Output
QuantileClipper(lower=0.01, upper=0.95) {'lower': 0.01, 'upper': 0.95}
NotFittedError: QuantileClipper is not fitted yet; call fit() first
learned low_=[700.0], high_=[3200.0]
capped training rows: 134 of 2250
upper=1.0 high_= 5690 validation R² 0.487
upper=0.99 high_= 4161 validation R² 0.439
upper=0.95 high_= 3220 validation R² 0.398
kept upper=1.0: test R² 0.545
ValueError: need 0 <= lower < upper <= 1, got 0.9 and 0.1

How it works:

  1. The class has two hooks and an __init__, about 25 lines. The package gives it get_params(), the repr, fit_transform(), NotFittedError, the checks of ragged rows and of the number of features, and a place in make_model(). That is the payoff of the template method and the registry of module 22.
  2. The constructor stores lower and upper unchanged, and _fit() validates them. So set_params() and get_params() stay simple, as in scikit-learn. The error appears when you call fit(), not when you build the object.
  3. Pipeline.__getitem__ (module 20) accepts a step name, so pipe['clip'].high_ reads the learned bound of the fitted step.
  4. Interpret the result: clipping makes the line worse here. The validation R² falls from 0.487 without clipping to 0.439 at the 99% quantile and to 0.398 at 95%, so the kept setting is upper=1.0, which clips nothing. Only that choice touches the test part, once: 0.545. Large houses are not errors: their high prices are real, and clipping their size hides the information that explains those prices. A transformer that follows every convention is still only a hypothesis. Choose it on validation data, and keep the test part for the final score.
Core

Write a small data-quality tool:

  • RecordSource, a Protocol: a name and an __iter__ that yields dict[str, str] records, again on every loop;
  • two sources that do not inherit from it: CsvSource(path), which opens the file again on each loop, and ListSource(name, records) for tests;
  • Check, an abstract base class for one column, with a concrete helper number(record) (a float, or None for a blank cell) and two abstract methods, failed(record) and __str__();
  • two checks, Blank(column) and OutOfRange(column, low, high) (a blank is not out of range);
  • CheckResult, a frozen dataclass, and profile(source, checks), which runs every check in one pass over the source.

Profile data/houses.csv twice with different checks, data/customers.csv once and a fake ListSource once. Finally, show that a check without failed() cannot be created. Then name the two SOLID principles that profile() follows by taking a RecordSource and by using only failed() and str() of a check, and say what would break if it took a CsvSource.

Expected output
data/houses.csv
blank lot_sqft 90 of 3000
blank school_rating 90 of 3000
data/houses.csv
school_rating outside [1, 10] 0 of 3000
price outside [150,000, 3,000,000] 13 of 3000
data/customers.csv
blank total_charges 10 of 5000
fake
blank lot_sqft 1 of 2
price outside [150,000, 3,000,000] 1 of 2
Can't instantiate abstract class Negative without an implementation for abstract method 'failed'
Starter
import csv
from abc import ABC, abstractmethod
from collections.abc import Iterable, Iterator
from dataclasses import dataclass
from typing import Protocol
type Record = dict[str, str]
# TODO: RecordSource (Protocol), CsvSource, ListSource
# TODO: Check (ABC) with number(), failed() and __str__(); Blank and OutOfRange
# TODO: CheckResult (frozen dataclass) and profile(source, checks) in one pass
def report(source, checks) -> None:
print(source.name)
for result in profile(source, checks):
print(" ", result)
# TODO: the four reports, then try to create a check without failed()
Hint 1

A generator method makes a re-iterable object: def __iter__(self): with open(...) as file: yield from csv.DictReader(file). Each for loop calls __iter__ again and opens the file again. A class that returned the same reader every time would be empty on the second loop.

Hint 2

profile() loops over the records once and, inside, over the checks: keep one failure counter per check. failures[i] += check.failed(record) adds 1 for True. An ABC raises TypeError when you create an instance of a subclass that still has an abstract method.

Solution
import csv
from abc import ABC, abstractmethod
from collections.abc import Iterable, Iterator
from dataclasses import dataclass
from typing import Protocol
type Record = dict[str, str]
class RecordSource(Protocol):
"""Anything with a name that yields records, again on every loop."""
name: str
def __iter__(self) -> Iterator[Record]: ...
class CsvSource:
def __init__(self, path: str) -> None:
self.path = path
self.name = path
def __iter__(self) -> Iterator[Record]:
with open(self.path, encoding="utf-8", newline="") as file:
yield from csv.DictReader(file) # a new pass over the file per loop
class ListSource:
def __init__(self, name: str, records: Iterable[Record]) -> None:
self.name = name
self.records = list(records)
def __iter__(self) -> Iterator[Record]:
return iter(self.records)
class Check(ABC):
"""One rule for one column. Subclasses must write failed() and __str__()."""
def __init__(self, column: str) -> None:
self.column = column
def number(self, record: Record) -> float | None:
text = record[self.column].strip()
return float(text) if text else None
@abstractmethod
def failed(self, record: Record) -> bool: ...
@abstractmethod
def __str__(self) -> str: ...
class Blank(Check):
def failed(self, record: Record) -> bool:
return self.number(record) is None
def __str__(self) -> str:
return f"blank {self.column}"
class OutOfRange(Check):
def __init__(self, column: str, low: float, high: float) -> None:
super().__init__(column)
self.low, self.high = low, high
def failed(self, record: Record) -> bool:
value = self.number(record)
return value is not None and not self.low <= value <= self.high
def __str__(self) -> str:
return f"{self.column} outside [{self.low:,}, {self.high:,}]"
@dataclass(frozen=True)
class CheckResult:
check: str
failures: int
total: int
def __str__(self) -> str:
return f"{self.check:<36} {self.failures:>4} of {self.total}"
def profile(source: RecordSource, checks: Iterable[Check]) -> list[CheckResult]:
"""Run every check in one pass over the source."""
checks = list(checks)
failures = [0] * len(checks)
total = 0
for record in source:
total += 1
for i, check in enumerate(checks):
failures[i] += check.failed(record)
pairs = zip(checks, failures, strict=True)
return [CheckResult(str(check), n, total) for check, n in pairs]
def report(source: RecordSource, checks: Iterable[Check]) -> None:
print(source.name)
for result in profile(source, checks):
print(" ", result)
houses = CsvSource("data/houses.csv")
report(houses, [Blank("lot_sqft"), Blank("school_rating")])
report(
houses,
[OutOfRange("school_rating", 1, 10), OutOfRange("price", 150_000, 3_000_000)],
)
report(CsvSource("data/customers.csv"), [Blank("total_charges")])
fake = ListSource(
"fake", [{"price": "99", "lot_sqft": ""}, {"price": "", "lot_sqft": "5"}]
)
report(fake, [Blank("lot_sqft"), OutOfRange("price", 150_000, 3_000_000)])
class Negative(Check):
def __str__(self) -> str:
return f"negative {self.column}"
try:
Negative("price")
except TypeError as error:
print(error)
results = profile(houses, [Blank("lot_sqft")])
assert results == [CheckResult("blank lot_sqft", 90, 3000)]
assert profile(houses, [Blank("lot_sqft")]) == results # the source is re-iterable
Output
data/houses.csv
blank lot_sqft 90 of 3000
blank school_rating 90 of 3000
data/houses.csv
school_rating outside [1, 10] 0 of 3000
price outside [150,000, 3,000,000] 13 of 3000
data/customers.csv
blank total_charges 10 of 5000
fake
blank lot_sqft 1 of 2
price outside [150,000, 3,000,000] 1 of 2
Can't instantiate abstract class Negative without an implementation for abstract method 'failed'

How it works:

  1. profile() depends on the RecordSource Protocol, and the caller injects the source. The real file and the fake list are interchangeable, so you can test the checks without a file. Neither source inherits anything: the Protocol matches by structure (module 19), and mypy checks the match.
  2. The checks use an ABC instead, because they share code (__init__ and number()) and must provide failed() and __str__(). The ABC refuses Negative("price") at creation time, before any record is checked. Duck typing would fail later, on the first record.
  3. CsvSource.__iter__ is a generator, so each loop opens a new file handle and closes it at the end. That is why the second report on houses sees all 3,000 rows again. One pass per profile() call reads the file once for any number of checks.
  4. The counts match the data dictionary: 90 blank lot_sqft, 90 blank school_rating and 10 blank total_charges. Of the 13 prices outside [150,000, 3,000,000], one, H0957 (117,500), is an injected outlier that the data dictionary lists. The other 7 injected outliers lie inside the range, so a fixed range misses them; price per square foot within a neighborhood (P3-03) finds them better. A range check finds candidates for review. It does not prove that a value is wrong or right.
  5. Two SOLID principles shape the design. Dependency inversion: profile() depends on the RecordSource abstraction, not on CsvSource, so a database or an API source works without a change and a test needs no file. Interface segregation: profile() uses only failed() and str() of a check, and a source needs only name and __iter__. Small interfaces keep the coupling low: each class knows little about the others, and each has one cohesive job.

P3-11 · Interpret a measurement, then fix: a slotted subclass

Section titled “P3-11 · Interpret a measurement, then fix: a slotted subclass”
Core

Interpret a measurement, then fix the bug: HouseRecord declares __slots__ to keep 3,000 houses small in memory. A colleague added LocatedHouse, a subclass with a neighborhood, and measured the bytes per record with tracemalloc. The starter prints this:

dict 184 bytes per record
HouseRecord 56 bytes per record
LocatedHouse 416 bytes per record
True {'neighborhood': 'Lakeview', 'prise': 1200000}

Explain both surprises: the subclass costs more than a dict, and the typo house.prise = ... was accepted. Then fix LocatedHouse so that it costs only a little more than HouseRecord, rejects the typo with AttributeError, and still has the inherited price_per_sqft property. Print the name of the rejected attribute, not the full error message, because the message differs between Python versions.

Expected output
dict 184 bytes per record
HouseRecord 56 bytes per record
LocatedHouse 64 bytes per record
False 453.51
AttributeError for 'prise'
Starter
import csv
import tracemalloc
from collections.abc import Callable
class HouseRecord:
__slots__ = ("house_id", "sqft", "price")
def __init__(self, house_id: str, sqft: int, price: int) -> None:
self.house_id = house_id
self.sqft = sqft
self.price = price
@property
def price_per_sqft(self) -> float:
return self.price / self.sqft
class LocatedHouse(HouseRecord):
def __init__(self, house_id: str, sqft: int, price: int, neighborhood: str) -> None:
super().__init__(house_id, sqft, price)
self.neighborhood = neighborhood
def traced_bytes(build: Callable[[tuple[str, int, int, str]], object]) -> int:
spare = [build(values) for values in parsed[:100]] # empty Python's free lists
tracemalloc.start()
records = [build(values) for values in parsed]
size = tracemalloc.get_traced_memory()[0]
tracemalloc.stop()
del records, spare
return size
def bytes_per_record(build: Callable[[tuple[str, int, int, str]], object]) -> float:
"""Memory of the records only: minus a list of the same length."""
return (traced_bytes(build) - traced_bytes(lambda v: None)) / len(parsed)
with open("data/houses.csv", encoding="utf-8", newline="") as file:
parsed = [
(r["house_id"], int(r["sqft"]), int(r["price"]), r["neighborhood"])
for r in csv.DictReader(file)
]
FIELDS = ("house_id", "sqft", "price", "neighborhood")
builders = {
"dict": lambda v: dict(zip(FIELDS, v, strict=True)),
"HouseRecord": lambda v: HouseRecord(*v[:3]),
"LocatedHouse": lambda v: LocatedHouse(*v),
}
for name, build in builders.items():
print(f"{name:<13} {bytes_per_record(build):6.0f} bytes per record")
house = LocatedHouse(*parsed[0])
house.prise = 1_200_000 # a typo
print(hasattr(house, "__dict__"), vars(house))
Hint 1

The last line of the starter answers half the question: hasattr(house, "__dict__") is True. Where did that __dict__ come from, when HouseRecord has none?

Hint 2

__slots__ works per class. A subclass without its own __slots__ gets a __dict__ again. Declare only the new names in the subclass: the parent’s slots are inherited.

Solution
import csv
import tracemalloc
from collections.abc import Callable
class HouseRecord:
__slots__ = ("house_id", "sqft", "price")
def __init__(self, house_id: str, sqft: int, price: int) -> None:
self.house_id = house_id
self.sqft = sqft
self.price = price
@property
def price_per_sqft(self) -> float:
return self.price / self.sqft
class LocatedHouse(HouseRecord):
__slots__ = ("neighborhood",) # only the new name; the parent has the others
def __init__(self, house_id: str, sqft: int, price: int, neighborhood: str) -> None:
super().__init__(house_id, sqft, price)
self.neighborhood = neighborhood
def traced_bytes(build: Callable[[tuple[str, int, int, str]], object]) -> int:
spare = [build(values) for values in parsed[:100]] # empty Python's free lists
tracemalloc.start()
records = [build(values) for values in parsed]
size = tracemalloc.get_traced_memory()[0]
tracemalloc.stop()
del records, spare
return size
def bytes_per_record(build: Callable[[tuple[str, int, int, str]], object]) -> float:
"""Memory of the records only: minus a list of the same length."""
return (traced_bytes(build) - traced_bytes(lambda v: None)) / len(parsed)
with open("data/houses.csv", encoding="utf-8", newline="") as file:
parsed = [
(r["house_id"], int(r["sqft"]), int(r["price"]), r["neighborhood"])
for r in csv.DictReader(file)
]
FIELDS = ("house_id", "sqft", "price", "neighborhood")
builders = {
"dict": lambda v: dict(zip(FIELDS, v, strict=True)),
"HouseRecord": lambda v: HouseRecord(*v[:3]),
"LocatedHouse": lambda v: LocatedHouse(*v),
}
for name, build in builders.items():
print(f"{name:<13} {bytes_per_record(build):6.0f} bytes per record")
house = LocatedHouse(*parsed[0])
print(hasattr(house, "__dict__"), f"{house.price_per_sqft:.2f}")
try:
house.prise = 1_200_000 # a typo
except AttributeError as error:
print("AttributeError for", repr(error.name))
sizes = {name: bytes_per_record(build) for name, build in builders.items()}
assert sizes["LocatedHouse"] < sizes["dict"] / 2
assert not hasattr(house, "__dict__") and house.price == 1_097_500
Output
dict 184 bytes per record
HouseRecord 56 bytes per record
LocatedHouse 64 bytes per record
False 453.51
AttributeError for 'prise'

How it works:

  1. Without __slots__ in LocatedHouse, every instance got a __dict__ for its one extra attribute, on top of the three slots. In this measurement, a record then costs 416 bytes, more than twice a plain dict of all four fields. The slots of the parent saved nothing.
  2. The same __dict__ accepted any new name, so the typo prise became a silent new attribute while price kept the old value. With __slots__ = ("neighborhood",), the instance has no __dict__, a record costs 64 bytes (8 more than HouseRecord, one slot), and the typo raises AttributeError.
  3. Properties work with slots, because a property lives on the class, not in the instance. price_per_sqft needs no storage at all.
  4. bytes_per_record() subtracts the memory of a list of None of the same length, so it counts only the records. The spare records empty Python’s free lists (caches of freed objects that are reused without a traced allocation) before the measurement, so the result does not depend on what ran before. The values (strings and ints) are created before the measurement, so it does not count them either. The numbers come from Python 3.13. Other versions give other numbers, but the order (subclass without slots ≫ dict ≫ slotted) holds.
  5. When to use this: __slots__ pays off for many small objects with a fixed set of fields. For a few records, a dataclass with slots=True gives the same saving and writes __slots__ for you, also in each subclass that is a slotted dataclass.

P3-12 · Fix the bug, then write a run log context manager

Section titled “P3-12 · Fix the bug, then write a run log context manager”
Core

Fix the bug, then write the code: the starter’s RunRecord dataclass should keep the name, status, duration, metrics and error of one analysis run. It fails as soon as Python defines it. Fix it, then write:

  • RunStatus, a StrEnum with OK and FAILED (given);
  • RunLog(name, history, *, clock=time.perf_counter), a context manager whose __enter__ starts the clock and returns a new RunRecord, and whose __exit__ stores the duration, marks a failed run with the error text, appends the record to the injected history list and never suppresses the exception;
  • summary(record), which formats a record with a match on its status.

Run three analyses on data/customers.csv with a fake clock that returns 0.0, 0.25, 1.0, 1.5, 2.0 and 2.75: the churn rate by contract, by plan, and by the column tier, which does not exist. Print the error that still reaches the caller, the three summaries, the failed record as JSON with asdict(), and whether the first two records share one metrics dict.

Expected output
the caller still sees the KeyError: 'tier'
by contract ok 0.25s month-to-month 0.296, one-year 0.088, two-year 0.032
by plan ok 0.50s basic 0.174, premium 0.296, standard 0.160
by tier FAILED 0.75s KeyError: 'tier'
{"name": "by tier", "status": "failed", "seconds": 0.75, "metrics": {}, "error": "KeyError: 'tier'"}
False
Starter
from dataclasses import dataclass
from enum import StrEnum, auto
class RunStatus(StrEnum):
OK = auto()
FAILED = auto()
@dataclass
class RunRecord:
name: str
status: RunStatus = RunStatus.OK
seconds: float = 0.0
metrics: dict[str, float] = {}
error: str = ""
# TODO: fix RunRecord, then write RunLog, summary() and the three runs
Hint 1

The error is ValueError: mutable default <class 'dict'> for field metrics is not allowed: use default_factory. Why would one default dict, created once with the class, be a problem for many records?

Hint 2

__exit__(self, exc_type, exc, tb) runs on success and on error; exc is None on success. Return False to let the exception continue. iter([...]).__next__ is a function that returns the next tick at each call, which makes a fine fake clock.

Solution
import csv
import json
import time
from collections.abc import Callable
from dataclasses import asdict, dataclass, field
from enum import StrEnum, auto
from types import TracebackType
class RunStatus(StrEnum):
OK = auto()
FAILED = auto()
@dataclass
class RunRecord:
name: str
status: RunStatus = RunStatus.OK
seconds: float = 0.0
metrics: dict[str, float] = field(default_factory=dict) # a new dict per run
error: str = ""
class RunLog:
"""Time a block, record its metrics, and keep the record even if it fails."""
def __init__(
self,
name: str,
history: list[RunRecord],
*,
clock: Callable[[], float] = time.perf_counter,
) -> None:
self.name = name
self.history = history # injected: the caller owns the list
self.clock = clock # injected: a test can pass a fake clock
def __enter__(self) -> RunRecord:
self._start = self.clock()
self.record = RunRecord(self.name)
return self.record
def __exit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> bool:
self.record.seconds = self.clock() - self._start
if exc is not None:
self.record.status = RunStatus.FAILED
self.record.error = f"{type(exc).__name__}: {exc}"
self.history.append(self.record)
return False # never hide the error: the caller decides
def summary(record: RunRecord) -> str:
match record.status:
case RunStatus.OK:
metrics = ", ".join(f"{k} {v:.3f}" for k, v in record.metrics.items())
return f"{record.name:<14} ok {record.seconds:4.2f}s {metrics}"
case RunStatus.FAILED:
return f"{record.name:<14} FAILED {record.seconds:4.2f}s {record.error}"
def churn_by(column: str) -> dict[str, float]:
with open("data/customers.csv", encoding="utf-8", newline="") as file:
rows = list(csv.DictReader(file))
groups: dict[str, list[int]] = {}
for row in rows:
groups.setdefault(row[column], []).append(int(row["churned"]))
return {key: sum(v) / len(v) for key, v in sorted(groups.items())}
fake_clock = iter([0.0, 0.25, 1.0, 1.5, 2.0, 2.75]).__next__ # 6 fixed ticks
history: list[RunRecord] = []
for name, column in [("by contract", "contract"), ("by plan", "plan")]:
with RunLog(name, history, clock=fake_clock) as run:
run.metrics.update(churn_by(column))
try:
with RunLog("by tier", history, clock=fake_clock) as run:
run.metrics.update(churn_by("tier"))
except KeyError as error:
print("the caller still sees the KeyError:", error)
for record in history:
print(summary(record))
print(json.dumps(asdict(history[-1])))
print(history[0].metrics is history[1].metrics)
assert [r.status for r in history] == ["ok", "ok", "failed"]
assert round(history[0].metrics["month-to-month"], 3) == 0.296
assert history[2].metrics == {} and history[2].seconds == 0.75
Output
the caller still sees the KeyError: 'tier'
by contract ok 0.25s month-to-month 0.296, one-year 0.088, two-year 0.032
by plan ok 0.50s basic 0.174, premium 0.296, standard 0.160
by tier FAILED 0.75s KeyError: 'tier'
{"name": "by tier", "status": "failed", "seconds": 0.75, "metrics": {}, "error": "KeyError: 'tier'"}
False

How it works:

  1. A default value is created once, when Python defines the class. A dict default would be shared by every RunRecord, so run.metrics.update(...) in one run would change all of them. Dataclasses refuse mutable defaults for this reason. field(default_factory=dict) calls dict() for each new record, and the last line, False, proves that the two runs have separate dicts.
  2. __exit__ runs whether the block succeeds or fails, so the failed run is still timed and recorded. It returns False, so the KeyError reaches the caller: a logger must never hide an error. Compare Section in P3-13, which suppresses one exception type on purpose.
  3. The clock and the history list are injected (module 22). Production code uses time.perf_counter and a real list or file; the test uses fixed ticks, so the durations 0.25, 0.50 and 0.75 are exact and the output never changes.
  4. match record.status with the dotted patterns RunStatus.OK and RunStatus.FAILED compares by value, so each case matches one member. A bare name such as case OK: would capture any value instead.
  5. asdict() converts the record, including the metrics dict, to plain Python values. Because RunStatus is a StrEnum, json.dumps writes it as the string "failed". The churn rates match the data dictionary: month-to-month 29.6%, one-year 8.8%, two-year 3.2%.

P3-13 · Predict, then rewrite: scores that behave like numbers

Section titled “P3-13 · Predict, then rewrite: scores that behave like numbers”
Challenge

Predict the output: Score compares by value with total_ordering, adds with + and supports sum(). Leaderboard has __len__ and __iter__ but no __contains__. Run is a plain dataclass, and Section is a context manager that suppresses only KeyError. Write down every line, in order, then run the script.

Then rewrite Score as a frozen dataclass with order=True, in which only value takes part in comparisons. Keep the custom __repr__, __str__, __add__ and __radd__. Show that the lines of the first five print calls that still apply are unchanged, and that a set of the three scores now works. Explain why it has 2 members, and whether that is a good design.

Acceptance criteria:

  • Write your prediction for all 17 lines before you run the code.
  • Your prediction matches the Output in the solution, line by line.
  • Your rewrite prints the 5 lines of the second Output, and you can explain each special method that Python called for each line of the first script.
Starter
from collections.abc import Iterator
from dataclasses import dataclass
from functools import total_ordering
@total_ordering
class Score:
def __init__(self, model: str, value: float) -> None:
self.model = model
self.value = value
def __repr__(self) -> str:
return f"Score({self.model!r}, {self.value})"
def __str__(self) -> str:
return f"{self.model}: {self.value:.2f}"
def __eq__(self, other: object) -> bool:
if not isinstance(other, Score):
return NotImplemented
return self.value == other.value
def __lt__(self, other: object) -> bool:
if not isinstance(other, Score):
return NotImplemented
return self.value < other.value
def __add__(self, other: object) -> "Score":
if not isinstance(other, Score):
return NotImplemented
return Score(f"{self.model}+{other.model}", self.value + other.value)
def __radd__(self, other: object) -> "Score":
return self if other == 0 else NotImplemented
class Leaderboard:
def __init__(self, scores: list[Score]) -> None:
self.scores = scores
def __len__(self) -> int:
return len(self.scores)
def __iter__(self) -> Iterator[Score]:
print(" (iter)")
return iter(self.scores)
@dataclass
class Run:
model: str
value: float
class Section:
def __init__(self, title: str) -> None:
self.title = title
def __enter__(self) -> "Section":
print(f"[{self.title}]")
return self
def __exit__(self, exc_type, exc, tb) -> bool:
print(f"[/{self.title}] {exc_type.__name__ if exc_type else 'ok'}")
return exc_type is KeyError
knn = Score("knn", 0.81)
tree = Score("tree", 0.81)
line = Score("line", 0.74)
print(knn, [knn])
print(knn == tree, knn is tree, knn != line, knn >= line)
print(Score.__hash__ is None)
print(max([knn, tree, line]), min([line, knn]) is line)
print(sum([line, knn]))
board = Leaderboard([knn, line])
print(bool(board), bool(Leaderboard([])))
print(Score("other", 0.74) in board)
print(Run("knn", 0.81) == Run("knn", 0.81), Run("knn", 0.81) == knn)
with Section("fit") as section:
print(section.title)
with Section("lookup"):
value = {}["missing"]
try:
with Section("score"):
combined = knn + 1
except TypeError as error:
print("TypeError:", error)
# TODO: write your prediction for each line, then rewrite Score as a dataclass
Hint 1

A list shows its items with repr(). Defining __eq__ sets __hash__ to None. sum() starts with 0 + first. Without __contains__, in loops over __iter__ and compares with ==. bool() falls back to __len__.

Hint 2

When a == b gets NotImplemented from both sides, Python falls back to identity. A dataclass __eq__ returns NotImplemented for an object of another class. __exit__ runs even when the block raises; a true return value suppresses the exception. For the rewrite: field(compare=False) takes a field out of ==, < and hash(), and a dataclass keeps a __repr__ that the class defines itself.

Solution
from collections.abc import Iterator
from dataclasses import dataclass
from functools import total_ordering
@total_ordering
class Score:
def __init__(self, model: str, value: float) -> None:
self.model = model
self.value = value
def __repr__(self) -> str:
return f"Score({self.model!r}, {self.value})"
def __str__(self) -> str:
return f"{self.model}: {self.value:.2f}"
def __eq__(self, other: object) -> bool:
if not isinstance(other, Score):
return NotImplemented
return self.value == other.value
def __lt__(self, other: object) -> bool:
if not isinstance(other, Score):
return NotImplemented
return self.value < other.value
def __add__(self, other: object) -> "Score":
if not isinstance(other, Score):
return NotImplemented
return Score(f"{self.model}+{other.model}", self.value + other.value)
def __radd__(self, other: object) -> "Score":
return self if other == 0 else NotImplemented
class Leaderboard:
def __init__(self, scores: list[Score]) -> None:
self.scores = scores
def __len__(self) -> int:
return len(self.scores)
def __iter__(self) -> Iterator[Score]:
print(" (iter)")
return iter(self.scores)
@dataclass
class Run:
model: str
value: float
class Section:
def __init__(self, title: str) -> None:
self.title = title
def __enter__(self) -> "Section":
print(f"[{self.title}]")
return self
def __exit__(self, exc_type, exc, tb) -> bool:
print(f"[/{self.title}] {exc_type.__name__ if exc_type else 'ok'}")
return exc_type is KeyError
knn = Score("knn", 0.81)
tree = Score("tree", 0.81)
line = Score("line", 0.74)
print(knn, [knn])
print(knn == tree, knn is tree, knn != line, knn >= line)
print(Score.__hash__ is None)
print(max([knn, tree, line]), min([line, knn]) is line)
print(sum([line, knn]))
board = Leaderboard([knn, line])
print(bool(board), bool(Leaderboard([])))
print(Score("other", 0.74) in board)
print(Run("knn", 0.81) == Run("knn", 0.81), Run("knn", 0.81) == knn)
with Section("fit") as section:
print(section.title)
with Section("lookup"):
value = {}["missing"]
try:
with Section("score"):
combined = knn + 1
except TypeError as error:
print("TypeError:", error)
assert sorted([knn, line, tree]) == [line, knn, tree]
Output
knn: 0.81 [Score('knn', 0.81)]
True False True True
True
knn: 0.81 True
line+knn: 1.55
True False
(iter)
True
True False
[fit]
fit
[/fit] ok
[lookup]
[/lookup] KeyError
[score]
[/score] TypeError
TypeError: unsupported operand type(s) for +: 'Score' and 'int'

How it works:

  1. print(knn) uses __str__; inside a list, print shows repr() of each item. knn == tree is True (same value) while knn is tree is False. total_ordering derives >= from __lt__ and __eq__.
  2. Score.__hash__ is None: defining __eq__ removes the inherited hash, so a Score cannot go in a set or be a dict key.
  3. max() returns the first of equal maximums, so knn wins over tree. sum() computes 0 + line (int.__add__ returns NotImplemented, then line.__radd__(0) returns line), then line + knn.
  4. bool(board) calls __len__. Score("other", 0.74) in board has no __contains__, so Python iterates (the (iter) line) and finds line, which is equal by value.
  5. The dataclass __eq__ compares field tuples of the same class. Run(...) == knn gets NotImplemented from both sides, so Python compares identities: False, without an error.
  6. __exit__ runs in all three blocks. It returns True only for KeyError, so the lookup error is suppressed and the script goes on. The TypeError of knn + 1 passes through __exit__ and reaches the except outside.

The rewrite:

from dataclasses import dataclass, field
@dataclass(frozen=True, order=True)
class Score:
model: str = field(compare=False) # only value takes part in ==, < and hash
value: float
def __repr__(self) -> str:
return f"Score({self.model!r}, {self.value})"
def __str__(self) -> str:
return f"{self.model}: {self.value:.2f}"
def __add__(self, other: object) -> "Score":
if not isinstance(other, Score):
return NotImplemented
return Score(f"{self.model}+{other.model}", self.value + other.value)
def __radd__(self, other: object) -> "Score":
return self if other == 0 else NotImplemented
knn = Score("knn", 0.81)
tree = Score("tree", 0.81)
line = Score("line", 0.74)
print(knn, [knn])
print(knn == tree, knn is tree, knn != line, knn >= line)
print(max([knn, tree, line]), min([line, knn]) is line)
print(sum([line, knn]))
print(len({knn, tree, line}), sorted({knn, line}))
assert hash(knn) == hash(tree)
Output
knn: 0.81 [Score('knn', 0.81)]
True False True True
knn: 0.81 True
line+knn: 1.55
2 [Score('line', 0.74), Score('knn', 0.81)]
  1. order=True and frozen=True generate __eq__, __lt__, the other comparisons and __hash__ from the fields that compare, here only value. The class keeps its own __repr__, so the output did not change. total_ordering is no longer needed.
  2. The set has 2 members because knn and tree are equal and have the same hash. That is consistent, but it is a questionable design: two different models with the same score are not the same result. A better design keeps equality on all fields and sorts a leaderboard with key=attrgetter("value"). Choose equality from what “the same object” means in your domain, not from the sort you need.

P3-14 · Interpret, then fix: a KNN regressor for house prices

Section titled “P3-14 · Interpret, then fix: a KNN regressor for house prices”
Challenge

Interpret, then extend minilearn: a colleague added a regressor by subclassing the classifier. On data/houses.csv (features sqft and distance_to_center_km, target price, train_test_split(test_size=0.25, random_state=42)), its predictions look fine, but score() returns 0.0. Explain the result with the Liskov rule. Then write a correct KNNRegressor:

  • it shares the neighbor search with the classifier through a NeighborsMixin that holds _fit_neighbors() and kneighbors(), instead of inheriting from KNNClassifier;
  • it inherits RegressorMixin and BaseEstimator, accepts the same n_neighbors and distance strategy as KNNClassifier, and registers itself as "knn_reg";
  • its prediction is the mean target of the Neighbor tuples that kneighbors() returns.

Choose n_neighbors from 5, 15 and 30 on a validation split of the training part (test_size=0.25, random_state=0), always with a StandardScaler in front, once for the two features and once for sqft alone. Then score four models on the test part, each once: the "mean" baseline, a LinearRegression on sqft, KNN on sqft and KNN on both features. The two KNN models on sqft and on both features separate the effect of a flexible fit from the effect of the second feature. Run it in the folder that holds minilearn/ (see Setup).

Expected output
KNNRegressor(n_neighbors=15, distance=Distance.EUCLIDEAN)
MRO: ['KNNRegressor', 'NeighborsMixin', 'RegressorMixin', 'PredictorMixin', 'BaseEstimator']
classifier: False
two features:
validation R²: k=5 0.693, k=15 0.693, k=30 0.700
sqft only:
validation R²: k=5 0.402, k=15 0.487, k=30 0.495
test R² mean -0.000
test R² line (sqft) 0.545
test R² knn k=30 (sqft) 0.586
test R² knn k=30 (2 features) 0.779
flexible fit adds 0.041, second feature adds 0.192
Starter
import csv
import statistics
from minilearn import KNNClassifier, Pipeline, StandardScaler, train_test_split
from minilearn.base import Rows
class KNNRegressor(KNNClassifier):
"""Predict the mean price of the k nearest houses."""
def _predict(self, X: Rows) -> list[float]:
return [statistics.fmean(n.label for n in self.kneighbors(row)) for row in X]
with open("data/houses.csv", encoding="utf-8", newline="") as file:
houses = list(csv.DictReader(file))
X = [[float(h["sqft"]), float(h["distance_to_center_km"])] for h in houses]
y = [float(h["price"]) for h in houses]
split = train_test_split(X, y, test_size=0.25, random_state=42)
model = Pipeline([("scale", StandardScaler()), ("knn", KNNRegressor(n_neighbors=10))])
model.fit(split.X_train, split.y_train)
print(model["knn"])
print("first 3 predictions:", [round(p) for p in model.predict(split.X_test[:3])])
print("true prices: ", [round(p) for p in split.y_test[:3]])
print("score:", model.score(split.X_test, split.y_test))
print("classes_:", len(model["knn"].classes_))
# TODO: explain the score, then write NeighborsMixin and a correct KNNRegressor
Hint 1

Follow model.score(): Pipeline.score() calls the last step’s score(). Which mixin does KNNRegressor get it from? What does that score() compute, and how often is a mean of 10 prices exactly equal to a true price?

Hint 2

Move the body of KNNClassifier._fit() (without classes_) and kneighbors() into the mixin. Give the mixin class-level annotations n_neighbors: int and distance: ..., so readers and mypy know what it expects from its host. Put the mixin first in the bases: (NeighborsMixin, RegressorMixin, BaseEstimator). Keep the test part out of the choice of k.

Solution

First, run the colleague’s version:

import csv
import statistics
from minilearn import KNNClassifier, Pipeline, StandardScaler, train_test_split
from minilearn.base import Rows
class KNNRegressor(KNNClassifier):
"""Predict the mean price of the k nearest houses."""
def _predict(self, X: Rows) -> list[float]:
return [statistics.fmean(n.label for n in self.kneighbors(row)) for row in X]
with open("data/houses.csv", encoding="utf-8", newline="") as file:
houses = list(csv.DictReader(file))
X = [[float(h["sqft"]), float(h["distance_to_center_km"])] for h in houses]
y = [float(h["price"]) for h in houses]
split = train_test_split(X, y, test_size=0.25, random_state=42)
model = Pipeline([("scale", StandardScaler()), ("knn", KNNRegressor(n_neighbors=10))])
model.fit(split.X_train, split.y_train)
print(model["knn"])
print("first 3 predictions:", [round(p) for p in model.predict(split.X_test[:3])])
print("true prices: ", [round(p) for p in split.y_test[:3]])
print("score:", model.score(split.X_test, split.y_test))
print("classes_:", len(model["knn"].classes_))
Output
KNNRegressor(n_neighbors=10, distance=Distance.EUCLIDEAN)
first 3 predictions: [923050, 355600, 407950]
true prices: [1097500, 435000, 366500]
score: 0.0
classes_: 1145

The predictions are plausible, but KNNRegressor is a KNNClassifier, so it inherits ClassifierMixin.score(): accuracy, the share of predictions exactly equal to the true price. A mean of 10 prices is almost never exactly a true price, so the score is 0.0. The subclass also inherits classes_, which treats 1,145 distinct prices as classes. It breaks the promises of its parent (Liskov substitution): code that treats it as a classifier gets regressions, and code that wants R² gets accuracy.

The fix:

import csv
import statistics
from collections.abc import Sequence
from typing import Any
from minilearn import (
BaseEstimator,
ClassifierMixin,
Distance,
LinearRegression,
Neighbor,
Pipeline,
RegressorMixin,
StandardScaler,
check_is_fitted,
get_distance,
make_model,
register,
train_test_split,
)
from minilearn.base import Rows
from minilearn.distances import DistanceFunc, Row
class NeighborsMixin:
"""The neighbor search that every k-nearest-neighbors model shares."""
n_neighbors: int
distance: Distance | str | DistanceFunc
def _fit_neighbors(self, X: Rows, y: list[Any]) -> None:
if self.n_neighbors < 1:
raise ValueError(f"n_neighbors must be >= 1, got {self.n_neighbors}")
self.distance_ = get_distance(self.distance) # the strategy
self.X_train_ = X
self.y_train_ = y
def kneighbors(self, row: Row) -> list[Neighbor]:
check_is_fitted(self)
pairs = zip(self.X_train_, self.y_train_, strict=True)
found = [
Neighbor(i, self.distance_(row, x), label)
for i, (x, label) in enumerate(pairs)
]
found.sort(key=lambda n: (n.distance, n.index)) # ties: lower row number
return found[: self.n_neighbors]
@register("knn_reg")
class KNNRegressor(NeighborsMixin, RegressorMixin, BaseEstimator):
"""Predict the mean target of the k nearest training rows."""
def __init__(
self,
n_neighbors: int = 5,
distance: Distance | str | DistanceFunc = Distance.EUCLIDEAN,
) -> None:
self.n_neighbors = n_neighbors
self.distance = distance
def _fit(self, X: Rows, y: list[float]) -> None:
self._fit_neighbors(X, y)
def _predict(self, X: Rows) -> list[float]:
return [statistics.fmean(n.label for n in self.kneighbors(row)) for row in X]
def knn_pipeline(k: int) -> Pipeline:
return Pipeline([("scale", StandardScaler()), ("knn", KNNRegressor(k))])
with open("data/houses.csv", encoding="utf-8", newline="") as file:
houses = list(csv.DictReader(file))
X = [[float(h["sqft"]), float(h["distance_to_center_km"])] for h in houses]
y = [float(h["price"]) for h in houses]
split = train_test_split(X, y, test_size=0.25, random_state=42)
inner = train_test_split(split.X_train, split.y_train, test_size=0.25, random_state=0)
def sqft_only(rows: Sequence[Sequence[float]]) -> Rows:
return [[row[0]] for row in rows]
def choose_k(X_fit: Rows, y_fit: list[float], X_val: Rows, y_val: list[float]) -> int:
"""Pick n_neighbors on the validation part only."""
scores = {}
for k in (5, 15, 30):
scores[k] = knn_pipeline(k).fit(X_fit, y_fit).score(X_val, y_val)
print(" validation R²:", ", ".join(f"k={k} {s:.3f}" for k, s in scores.items()))
return max(scores, key=scores.__getitem__)
print(make_model("knn_reg", n_neighbors=15))
print("MRO:", [c.__name__ for c in KNNRegressor.__mro__[:5]])
print("classifier:", isinstance(KNNRegressor(), ClassifierMixin))
print("two features:")
k2 = choose_k(inner.X_train, inner.y_train, inner.X_test, inner.y_test)
print("sqft only:")
k1 = choose_k(
sqft_only(inner.X_train), inner.y_train, sqft_only(inner.X_test), inner.y_test
)
X_tr1, X_te1 = sqft_only(split.X_train), sqft_only(split.X_test)
X_tr2, X_te2 = split.X_train, split.X_test
candidates = [
("mean", make_model("mean"), X_tr2, X_te2),
("line (sqft)", LinearRegression(), X_tr1, X_te1),
(f"knn k={k1} (sqft)", knn_pipeline(k1), X_tr1, X_te1),
(f"knn k={k2} (2 features)", knn_pipeline(k2), X_tr2, X_te2),
]
test_r2 = {}
for name, model, X_fit, X_eval in candidates: # each is scored on the test part once
test_r2[name] = model.fit(X_fit, split.y_train).score(X_eval, split.y_test)
print(f"test R² {name:<22} {test_r2[name]:6.3f}")
r2 = list(test_r2.values())
print(f"flexible fit adds {r2[2] - r2[1]:.3f}, second feature adds {r2[3] - r2[2]:.3f}")
assert isinstance(candidates[-1][1]["knn"], RegressorMixin)
assert r2[0] < r2[1] < r2[2] < r2[3]
Output
KNNRegressor(n_neighbors=15, distance=Distance.EUCLIDEAN)
MRO: ['KNNRegressor', 'NeighborsMixin', 'RegressorMixin', 'PredictorMixin', 'BaseEstimator']
classifier: False
two features:
validation R²: k=5 0.693, k=15 0.693, k=30 0.700
sqft only:
validation R²: k=5 0.402, k=15 0.487, k=30 0.495
test R² mean -0.000
test R² line (sqft) 0.545
test R² knn k=30 (sqft) 0.586
test R² knn k=30 (2 features) 0.779
flexible fit adds 0.041, second feature adds 0.192

How it works:

  1. KNNRegressor is not a classifier any more, and score() now comes from RegressorMixin: R². The MRO shows the order: the mixin first, then RegressorMixin and BaseEstimator.
  2. NeighborsMixin holds the code that both KNN models really share: validation of n_neighbors, the distance strategy, the training rows and the search with deterministic ties. Inheritance from a small mixin reuses code without inheriting an interface that does not fit. In the package, move kneighbors() from KNNClassifier into this mixin, so that the code exists once.
  3. The distance parameter is the strategy of module 22: KNNRegressor(15, distance="manhattan") or any function of two rows works without a change in the class. The Neighbor NamedTuple of module 21 makes n.label readable.
  4. The choice of k uses only the validation part, separately for each feature set. Each model meets the test part once, at the end, so its R² is an honest estimate.
  5. Interpret the result: the mean baseline scores about 0, as it should. The line on sqft explains 54.5% of the variance. On the same single feature, KNN reaches 0.586: the flexible fit adds about 0.04. Adding the distance to the center lifts KNN to 0.779, about 0.19 more. The second feature matters much more than the flexible fit. (The minilearn LinearRegression takes one feature only, so a line on both features is not on the list.) The scaler is essential: without it, sqft (hundreds to thousands) would dominate a distance in km.

P3-15 · Refactor: a sensor monitor with observers

Section titled “P3-15 · Refactor: a sensor monitor with observers”
Challenge

Refactor procedural code into OOP: the starter classifies every reading of data/sensors.csv with hard-coded thresholds, counts the statuses per sensor, prints the first 3 alerts (a sensor that enters fail) and checks the result against the file’s status column, all in one loop with module-level state. Rewrite it with:

  • Status, an IntEnum whose str() is the text of the file;
  • Reading, a frozen, slotted dataclass with a from_row() class method (a blank cell becomes None);
  • Thresholds, a frozen, slotted, keyword-only dataclass with the four limits as defaults, a __post_init__ that rejects a warn limit that is not below its fail limit, and classify(reading);
  • Observer, a base class with the no-op events on_reading(reading, status) and on_alert(reading), and three observers: StatusCounts (a dataclass whose counts dict starts empty for each instance), AlertLog(log=print, limit=3) and Agreement;
  • SensorMonitor(thresholds, observers) with process(readings), which prints nothing itself and detects an alert with a match on the pair (previous status, new status);
  • run(readings, *, log=print, thresholds=...), which logs the report and returns its lines.

The first 8 lines must equal the output of the starter. Then run run() on three fake readings with a list as the logger, and show the threshold check and the keyword-only rule.

Expected output
ALERT 2024-05-01T08:00:00 S4 fail (t=24.88, v=12.92)
ALERT 2024-05-02T13:20:00 S2 fail (t=44.89, v=2.96)
ALERT 2024-05-02T18:20:00 S4 fail (t=27.42, v=14.79)
S1: ok 2002 warn 14 fail 0
S2: ok 1994 warn 17 fail 5
S3: ok 1994 warn 22 fail 0
S4: ok 1598 warn 399 fail 19
alerts: 22, agree with the file: 8063 of 8064
fake | ALERT t1 S9 fail (t=20.0, v=12.0)
fake | S9: ok 0 warn 1 fail 2
fake | alerts: 1, agree with the file: 2 of 3
ValueError: each warn threshold must be below its fail threshold
TypeError: Thresholds.__init__() takes 1 positional argument but 5 were given
Starter
import csv
TEMP_WARN, TEMP_FAIL = 33.0, 42.0
VIB_WARN, VIB_FAIL = 4.5, 11.2
counts = {}
last = {}
alerts = 0
agree = 0
with open("data/sensors.csv", encoding="utf-8", newline="") as file:
rows = list(csv.DictReader(file))
for row in rows:
t = float(row["temperature_c"]) if row["temperature_c"] else None
v = float(row["vibration_mm_s"]) if row["vibration_mm_s"] else None
if (v is not None and v >= VIB_FAIL) or (t is not None and t >= TEMP_FAIL):
status = "fail"
elif (v is not None and v >= VIB_WARN) or (t is not None and t >= TEMP_WARN):
status = "warn"
else:
status = "ok"
sensor = row["sensor_id"]
counts.setdefault(sensor, {"ok": 0, "warn": 0, "fail": 0})
counts[sensor][status] += 1
if status == "fail" and last.get(sensor) != "fail":
alerts += 1
if alerts <= 3:
print(f"ALERT {row['timestamp']} {sensor} fail (t={t}, v={v})")
last[sensor] = status
agree += status == row["status"]
for sensor in sorted(counts):
c = counts[sensor]
print(f"{sensor}: ok {c['ok']:>4} warn {c['warn']:>3} fail {c['fail']:>2}")
print(f"alerts: {alerts}, agree with the file: {agree} of {len(rows)}")
# TODO: rewrite with Status, Reading, Thresholds, observers and SensorMonitor
Hint 1

Sort the state of the loop by who needs it. The counts, the alert counter and the agreement counter are three independent observers. The last status per sensor belongs to the monitor, because it decides when an alert event happens.

Hint 2

Status[row["status"].upper()] converts the file text. ruff’s rule B008 (in its B rule set, which this course turns on) flags a call such as Thresholds() in a default argument, because the object is created once and shared by every call. Because Thresholds is frozen, sharing it is safe. A named module constant, DEFAULT_THRESHOLDS = Thresholds(), says so and satisfies the rule. case (Status.OK | Status.WARN, Status.FAIL): matches a tuple of two enum members.

Solution
import csv
from collections import Counter
from collections.abc import Callable, Iterable
from dataclasses import dataclass, field
from enum import IntEnum
from typing import Self
class Status(IntEnum):
OK = 0
WARN = 1
FAIL = 2
def __str__(self) -> str:
return self.name.lower() # the text of the CSV file
@dataclass(frozen=True, slots=True)
class Reading:
timestamp: str
sensor_id: str
temperature: float | None
vibration: float | None
status: Status # the status written in the file
@classmethod
def from_row(cls, row: dict[str, str]) -> Self:
def number(text: str) -> float | None:
return float(text) if text else None
return cls(
row["timestamp"],
row["sensor_id"],
number(row["temperature_c"]),
number(row["vibration_mm_s"]),
Status[row["status"].upper()],
)
@dataclass(frozen=True, slots=True, kw_only=True)
class Thresholds:
temp_warn: float = 33.0
temp_fail: float = 42.0
vib_warn: float = 4.5
vib_fail: float = 11.2
def __post_init__(self) -> None:
if not (self.temp_warn < self.temp_fail and self.vib_warn < self.vib_fail):
raise ValueError("each warn threshold must be below its fail threshold")
def classify(self, reading: Reading) -> Status:
t, v = reading.temperature, reading.vibration
def at_least(value: float | None, limit: float) -> bool:
return value is not None and value >= limit
if at_least(v, self.vib_fail) or at_least(t, self.temp_fail):
return Status.FAIL
if at_least(v, self.vib_warn) or at_least(t, self.temp_warn):
return Status.WARN
return Status.OK
class Observer:
"""Base observer: every event does nothing until a subclass overrides it."""
def on_reading(self, reading: Reading, status: Status) -> None: ...
def on_alert(self, reading: Reading) -> None: ...
@dataclass
class StatusCounts(Observer):
counts: dict[str, Counter[Status]] = field(default_factory=dict)
def on_reading(self, reading: Reading, status: Status) -> None:
self.counts.setdefault(reading.sensor_id, Counter())[status] += 1
def report(self) -> list[str]:
return [
f"{sensor}: ok {c[Status.OK]:>4} warn {c[Status.WARN]:>3} "
f"fail {c[Status.FAIL]:>2}"
for sensor, c in sorted(self.counts.items())
]
class AlertLog(Observer):
def __init__(self, log: Callable[[str], None] = print, limit: int = 3) -> None:
self.log = log
self.limit = limit
self.alerts = 0
def on_alert(self, reading: Reading) -> None:
self.alerts += 1
if self.alerts <= self.limit:
r = reading
self.log(
f"ALERT {r.timestamp} {r.sensor_id} fail "
f"(t={r.temperature}, v={r.vibration})"
)
class Agreement(Observer):
def __init__(self) -> None:
self.agree = self.total = 0
def on_reading(self, reading: Reading, status: Status) -> None:
self.total += 1
self.agree += status == reading.status
class SensorMonitor:
"""Classify each reading and tell the observers. It prints nothing itself."""
def __init__(self, thresholds: Thresholds, observers: Iterable[Observer]) -> None:
self.thresholds = thresholds
self.observers = list(observers)
self._last: dict[str, Status] = {}
def process(self, readings: Iterable[Reading]) -> None:
for reading in readings:
status = self.thresholds.classify(reading)
for observer in self.observers:
observer.on_reading(reading, status)
previous = self._last.get(reading.sensor_id, Status.OK)
match (previous, status):
case (Status.OK | Status.WARN, Status.FAIL): # entered fail
for observer in self.observers:
observer.on_alert(reading)
case _:
pass
self._last[reading.sensor_id] = status
def read_readings(path: str) -> list[Reading]:
with open(path, encoding="utf-8", newline="") as file:
return [Reading.from_row(row) for row in csv.DictReader(file)]
DEFAULT_THRESHOLDS = Thresholds()
def run(
readings: Iterable[Reading],
*,
log: Callable[[str], None] = print,
thresholds: Thresholds = DEFAULT_THRESHOLDS,
) -> list[str]:
"""Monitor the readings, log the report and return its lines."""
counts, alerts, agreement = StatusCounts(), AlertLog(log), Agreement()
SensorMonitor(thresholds, [counts, alerts, agreement]).process(readings)
lines = [
*counts.report(),
f"alerts: {alerts.alerts}, agree with the file: "
f"{agreement.agree} of {agreement.total}",
]
for line in lines:
log(line)
return lines
report = run(read_readings("data/sensors.csv"))
fake = [
Reading("t1", "S9", 20.0, 12.0, Status.FAIL),
Reading("t2", "S9", None, 13.0, Status.FAIL),
Reading("t3", "S9", 34.0, None, Status.OK),
]
logged: list[str] = []
run(fake, log=logged.append)
for line in logged:
print("fake |", line)
try:
Thresholds(vib_warn=12.0)
except ValueError as error:
print("ValueError:", error)
try:
Thresholds(33.0, 42.0, 4.5, 11.2) # type: ignore[misc]
except TypeError as error:
print("TypeError:", error)
assert report[-1] == "alerts: 22, agree with the file: 8063 of 8064"
assert logged[1] == "S9: ok 0 warn 1 fail 2"
assert Status.FAIL > Status.WARN and str(Status.WARN) == "warn"
Output
ALERT 2024-05-01T08:00:00 S4 fail (t=24.88, v=12.92)
ALERT 2024-05-02T13:20:00 S2 fail (t=44.89, v=2.96)
ALERT 2024-05-02T18:20:00 S4 fail (t=27.42, v=14.79)
S1: ok 2002 warn 14 fail 0
S2: ok 1994 warn 17 fail 5
S3: ok 1994 warn 22 fail 0
S4: ok 1598 warn 399 fail 19
alerts: 22, agree with the file: 8063 of 8064
fake | ALERT t1 S9 fail (t=20.0, v=12.0)
fake | S9: ok 0 warn 1 fail 2
fake | alerts: 1, agree with the file: 2 of 3
ValueError: each warn threshold must be below its fail threshold
TypeError: Thresholds.__init__() takes 1 positional argument but 5 were given

How it works:

  1. The first 8 lines equal the procedural output, which is the characterization check of the refactoring (module 13). The asserts pin the last line.
  2. SensorMonitor knows only the Observer events. It does not know what its observers count or where they write. A new observer, such as one that sends an e-mail, needs no change in the monitor (open/closed), and each observer has one job (single responsibility).
  3. run() takes the readings and the logger as arguments: dependency injection. The test passes three fake readings and list.append as the logger, so it needs no file and captures every line. The fake shows that a second fail in a row is not a new alert.
  4. Reading and Thresholds are frozen, slotted dataclasses: 8,064 small records with fixed fields and no __dict__, safe to share. kw_only=True makes Thresholds(33.0, 42.0, 4.5, 11.2) a TypeError, so nobody can swap two limits by position. __post_init__ rejects vib_warn=12.0 before any reading is classified. StatusCounts uses field(default_factory=dict), so each instance gets its own dict. Status is an IntEnum, so severities compare (FAIL > WARN), and its __str__ gives back the text of the file.
  5. The match on (previous, status) names the one transition that raises an alert: from OK or WARN into FAIL. Dotted names such as Status.FAIL are value patterns. A recovery event would be one more case, with no new flag variable.
  6. Interpret the result: the classification agrees with the file on 8,063 of 8,064 readings. The one difference is the last S4 reading (2024-05-14T23:50), whose vibration cell is blank. The file computed its status before the blanks were added (see the data dictionary), so it says warn, while a rule that sees no vibration says ok. That is why S4 shows 399 warnings here and 400 in the file.

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

Skill area Not yet Getting there Ready
18. Classes and objects: attributes, methods, properties You keep state in module-level dicts and pass it to functions. You write classes, but a shared mutable class attribute or a mangled name surprises you. You place each attribute in the instance or the class on purpose, validate with property setters, and write @classmethod constructors and @staticmethod helpers.
19. Inheritance and polymorphism: super(), MRO, mixins, ABCs, Protocols You copy code between similar classes. You subclass, but break a cooperative super() chain or inherit an interface that does not fit. You predict the MRO of a diamond, repair a cooperative super() chain, share code through a small mixin instead of an unfitting parent, and pick an ABC or a Protocol with a reason.
20. The Python data model: special methods Your objects print as <object at 0x...> and need helper functions for everything. You write __repr__ and __len__, but forget NotImplemented or the hash rules. You make objects work with len(), in, slicing, sum(), operators and comparisons, write a context manager that records failures without hiding them, and predict which special method Python calls.
21. Dataclasses, enums and slots You use dicts and strings for every record and choice. You write dataclasses, but cannot choose between frozen, order, slots, a NamedTuple, a TypedDict and an Enum. You choose the record type and its options (frozen, order, slots, kw_only, default_factory) by how it is used, validate in __post_init__, convert with replace() and asdict(), match on enum members, and measure what __slots__ saves.
22. Design principles and patterns You add if branches for every new case. You know the pattern names, but apply them where a function would do. You apply strategy, factory, template method and observer, name the SOLID principle a design follows or breaks, inject dependencies for tests, extend minilearn within its conventions and say when a pattern is over-engineering.

You are ready for Part 4 when you can:

  • Solve at least 10 of the 15 exercises without opening the solution, including one challenge.
  • Predict the output of P3-01 and P3-13 with at most one wrong line each, and the MRO of the diamond in P3-05.
  • Explain where Python finds an attribute (instance, class, MRO) and why a name with two leading underscores hides from subclasses.
  • Write a class with a validating property, a @classmethod constructor and a @staticmethod helper.
  • Repair a cooperative chain in a diamond, and spot a subclass that breaks its parent’s promises.
  • Give a class __repr__, container methods, operators with NotImplemented and __radd__, and value-based equality with a correct hash.
  • Write a context manager whose __exit__ records an error and lets it continue.
  • Choose between a dataclass (frozen, ordered, slotted or keyword-only), a NamedTuple, a TypedDict, an Enum, a plain class and composition, with one reason each.
  • Explain the mutable-default error of dataclasses and fix it with default_factory, and measure the memory of slotted records with tracemalloc.
  • Refactor a procedural script into small classes with injected I/O and prove with a characterization check that the output did not change.
  • Apply the strategy and observer patterns, name dependency inversion and interface segregation in a design, and say when a plain function is enough.
  • Add a transformer and an estimator to minilearn that follow its conventions, choose their settings on validation data and score them once on the test part.

Rated “Not yet” in a row? Review that module’s lesson and cheat sheet, redo two of its core exercises, then try the matching checkpoint exercise again. When every row reads “Getting there” or “Ready”, move on to Part 4, module 23: NumPy. Part 4 builds on these skills: a NumPy array is an object whose special methods make +, *, [] and len() work on whole arrays, and a pandas DataFrame is a container class like the ones you wrote here.