Skip to content

21. Dataclasses, enums and slots — Exercises

These exercises practice every idea of the dataclasses, enums and slots lesson. They use the course data: customers, sensor readings, houses, stores, sales lines and the settings in data/config.json.

How to work:

  1. Read the task and the expected output.
  2. Copy the setup block and the starter code into a script (for example exercise.py). Replace each to-do comment with your code.
  3. Run the script with python exercise.py. Compare your output with the expected output.
  4. Stuck? Open one hint at a time. Open the solution only after a real attempt.

Each solution ends with assert checks. Add the same checks to your own code.

Every exercise can use this helper. Put it at the top of your script.

import csv
def read_csv(path: str) -> list[dict[str, str]]:
"""Read a CSV file into a list of dicts, one per row (all values are text)."""
with open(path, encoding="utf-8", newline="") as f:
return list(csv.DictReader(f))
Warm-up

After each training run, a script records the model, the number of training rows and the test score. Write a dataclass FitReport with the fields model (str), n_train (int) and test_score (float). Create two equal reports for "KNNClassifier(n_neighbors=15)" with 938 rows and a score of 0.824. Print the first report, then whether the two are equal and whether they are the same object, then a short summary line.

Expected output
FitReport(model='KNNClassifier(n_neighbors=15)', n_train=938, test_score=0.824)
True False
KNNClassifier(n_neighbors=15): 82.4%
Starter
from dataclasses import dataclass
# TODO: define FitReport with three annotated fields
# TODO: create two equal reports, knn and again
# TODO: print knn, then knn == again and knn is again, then the summary line
Hint 1

A dataclass is a class with @dataclass above it and one annotated name per field, such as model: str.

Hint 2

The summary line is f"{knn.model}: {knn.test_score:.1%}". The format spec .1% multiplies by 100 and adds a percent sign.

Solution
from dataclasses import dataclass
@dataclass
class FitReport:
model: str
n_train: int
test_score: float
knn = FitReport("KNNClassifier(n_neighbors=15)", 938, 0.824)
again = FitReport("KNNClassifier(n_neighbors=15)", 938, 0.824)
print(knn)
print(knn == again, knn is again)
print(f"{knn.model}: {knn.test_score:.1%}")
assert knn == again and knn is not again
assert knn != FitReport("KNNClassifier(n_neighbors=1)", 938, 0.696)
Output
FitReport(model='KNNClassifier(n_neighbors=15)', n_train=938, test_score=0.824)
True False
KNNClassifier(n_neighbors=15): 82.4%

How it works:

  1. @dataclass reads the three annotations and generates __init__(self, model, n_train, test_score).
  2. The generated __repr__ shows the class name and every field with repr(), so the model name keeps its quotes.
  3. The generated __eq__ compares the fields as a tuple. The two reports are equal but they are two objects, so is gives False.

Alternative: a typing.NamedTuple with the same three fields prints and compares the same way here. It is also a tuple, so it unpacks with model, n_train, score = knn, but it also equals the plain tuple ("KNNClassifier(n_neighbors=15)", 938, 0.824).

Warm-up

Fix the bug: this class should store tags for each experiment, but Python refuses to create it: ValueError: mutable default <class 'list'> for field tags is not allowed: use default_factory. Fix the field so that each experiment gets its own empty list. Then tag only the first experiment.

Expected output
Experiment(name='knn-k5', tags=['baseline'])
Experiment(name='knn-k15', tags=[])
Starter
from dataclasses import dataclass
@dataclass
class Experiment:
name: str
tags: list[str] = [] # TODO: fix this field
knn_5 = Experiment("knn-k5")
knn_15 = Experiment("knn-k15")
knn_5.tags.append("baseline")
print(knn_5)
print(knn_15)
Hint 1

The error message names the fix. Import field from dataclasses.

Hint 2

field(default_factory=list) calls list() once for each new instance.

Solution
from dataclasses import dataclass, field
@dataclass
class Experiment:
name: str
tags: list[str] = field(default_factory=list)
knn_5 = Experiment("knn-k5")
knn_15 = Experiment("knn-k15")
knn_5.tags.append("baseline")
print(knn_5)
print(knn_15)
assert knn_15.tags == []
assert knn_5.tags is not knn_15.tags
Output
Experiment(name='knn-k5', tags=['baseline'])
Experiment(name='knn-k15', tags=[])

How it works:

  1. The class body runs once. A list written there would be one object shared by every instance, the mutable default gotcha of module 13.
  2. @dataclass refuses such a default with the ValueError from the task.
  3. default_factory=list stores the function list, not a list. The generated __init__ calls it for each new object, so each experiment owns its list.

Alternative: a tuple default is allowed, because a tuple is immutable: tags: tuple[str, ...] = (). You then “add” a tag with knn_5.tags += ("baseline",), which builds a new tuple.

M21-W03 · Predict the output: equality and compare=False

Section titled “M21-W03 · Predict the output: equality and compare=False”
Warm-up

Predict the output: read the code and write down the five lines it prints. Then run it.

Acceptance criteria:

  • Write your prediction for every line before you run the code.
  • Run the code. Your prediction matches the Output in the solution, line by line.
  • For each line you got wrong, you can name the rule that explains it.
Starter
from dataclasses import dataclass, field
@dataclass
class Reading:
sensor_id: str
temperature_c: float
note: str = field(default="", compare=False)
a = Reading("S1", 20.21)
b = Reading("S1", 20.21, note="checked by hand")
c = Reading("S2", 20.21)
print(a)
print(a == b, a == c)
print(b)
print(Reading.__hash__ is None)
print([r.sensor_id for r in (a, b, c)].count("S1"))
Hint 1

compare=False removes a field from ==. Does it also remove it from the repr?

Hint 2

A dataclass with eq=True (the default) and without frozen=True gets __hash__ = None.

Solution
from dataclasses import dataclass, field
@dataclass
class Reading:
sensor_id: str
temperature_c: float
note: str = field(default="", compare=False)
a = Reading("S1", 20.21)
b = Reading("S1", 20.21, note="checked by hand")
c = Reading("S2", 20.21)
print(a)
print(a == b, a == c)
print(b)
print(Reading.__hash__ is None)
print([r.sensor_id for r in (a, b, c)].count("S1"))
assert a == b and a != c
Output
Reading(sensor_id='S1', temperature_c=20.21, note='')
True False
Reading(sensor_id='S1', temperature_c=20.21, note='checked by hand')
True
2

How it works:

  1. Line 1: the repr shows every field, also note with its default ''. compare=False does not hide a field; repr=False would.
  2. Line 2: a == b compares only sensor_id and temperature_c, so the different notes do not matter. a == c is False because the sensor ids differ.
  3. Line 3: b shows its note.
  4. Line 4: the class defines __eq__ and is not frozen, so @dataclass sets __hash__ to None. Instances are unhashable.
  5. Line 5: two of the three readings come from sensor S1.
Warm-up

data/config.json has thresholds.churn_probability, the probability above which the churn model flags a customer. Write a frozen dataclass DecisionThreshold with one field value: float and a __post_init__ that rejects values outside [0, 1] with ValueError("threshold must be in [0, 1], got ..."). Load the value from the file. Show that an assignment fails, make a stricter copy with replace(), and show that 1.5 is rejected.

Expected output
DecisionThreshold(value=0.5)
FrozenInstanceError: cannot assign to field 'value'
DecisionThreshold(value=0.3) DecisionThreshold(value=0.5)
ValueError: threshold must be in [0, 1], got 1.5
Starter
import json
from dataclasses import FrozenInstanceError, dataclass, replace
# TODO: the frozen dataclass with __post_init__
with open("data/config.json", encoding="utf-8") as f:
value = json.load(f)["thresholds"]["churn_probability"]
# TODO: create the threshold and print it
# TODO: try threshold.value = 0.3 and print the error type and message
# TODO: print replace(threshold, value=0.3) and threshold
# TODO: try DecisionThreshold(1.5) and print the error type and message
Hint 1

@dataclass(frozen=True). In __post_init__, test if not 0 <= self.value <= 1: and raise.

Hint 2

Catch each error with except FrozenInstanceError as exc: or except ValueError as exc: and print f"{type(exc).__name__}: {exc}".

Solution
import json
from dataclasses import FrozenInstanceError, dataclass, replace
@dataclass(frozen=True)
class DecisionThreshold:
value: float
def __post_init__(self) -> None:
if not 0 <= self.value <= 1:
raise ValueError(f"threshold must be in [0, 1], got {self.value}")
with open("data/config.json", encoding="utf-8") as f:
value = json.load(f)["thresholds"]["churn_probability"]
threshold = DecisionThreshold(value)
print(threshold)
try:
threshold.value = 0.3
except FrozenInstanceError as exc:
print(f"{type(exc).__name__}: {exc}")
stricter = replace(threshold, value=0.3)
print(stricter, threshold)
try:
DecisionThreshold(1.5)
except ValueError as exc:
print(f"{type(exc).__name__}: {exc}")
assert threshold.value == 0.5 and stricter.value == 0.3
assert hash(threshold) == hash(DecisionThreshold(0.5))
Output
DecisionThreshold(value=0.5)
FrozenInstanceError: cannot assign to field 'value'
DecisionThreshold(value=0.3) DecisionThreshold(value=0.5)
ValueError: threshold must be in [0, 1], got 1.5

How it works:

  1. frozen=True blocks every assignment after __init__ with FrozenInstanceError.
  2. replace() builds a new object through __init__, so the copy is validated too, and the original stays at 0.5.
  3. A frozen dataclass is hashable, so a threshold can be a dict key, for example in a table of costs per threshold.

Alternative: a lower threshold flags more customers. Module 36 chooses it from the precision-recall trade-off instead of a fixed config value.

M21-W05 · Parse sensor status codes with StrEnum

Section titled “M21-W05 · Parse sensor status codes with StrEnum”
Warm-up

The status column of data/sensors.csv holds ok, warn or fail. Define Status as a StrEnum with auto(). Convert the whole column, count the members with a Counter, and print the counts in the order of the enum. Then show that a lookup by value returns the member itself.

Expected output
ok 7,587
warn 453
fail 24
True True
Starter
from collections import Counter
from enum import StrEnum, auto
class Status(StrEnum):
OK = auto()
# TODO: WARN and FAIL
rows = read_csv("data/sensors.csv")
# TODO: convert each row's status with Status(...), count, and print in enum order
# TODO: print Status("warn") is Status.WARN
Hint 1

In a StrEnum, auto() gives the lowercase member name, so OK = auto() has the value "ok".

Hint 2

for status in Status: visits the members in definition order. Format a count with :>6,.

Solution
from collections import Counter
from enum import StrEnum, auto
class Status(StrEnum):
OK = auto()
WARN = auto()
FAIL = auto()
rows = read_csv("data/sensors.csv")
counts = Counter(Status(row["status"]) for row in rows)
for status in Status:
print(f"{status:<5} {counts[status]:>6,}")
print(Status("warn") is Status.WARN, Status.OK == "ok")
assert sum(counts.values()) == 8064
assert counts[Status.FAIL] == 24
Output
ok 7,587
warn 453
fail 24
True True

How it works:

  1. Status(row["status"]) looks a member up by its value. An unexpected code such as "error" would raise ValueError at once.
  2. The members are hashable, so they work as Counter keys.
  3. f"{status:<5}" formats a StrEnum member like its string value.
  4. Each member is a singleton, so the lookup returns the very object Status.WARN.

Alternative: without the enum, Counter(row["status"] for row in rows) gives the same counts, but a typo such as counts["wran"] returns 0 silently instead of failing.

M21-W06 · Predict the output: Enum and StrEnum

Section titled “M21-W06 · Predict the output: Enum and StrEnum”
Warm-up

Predict the output: the sales channel (online or store in data/sales.csv) is a StrEnum, the region a plain Enum with auto(). Write down the five lines before you run the code.

Acceptance criteria:

  • Write your prediction for every line before you run the code.
  • Run the code. Your prediction matches the Output in the solution, line by line.
  • For each line you got wrong, you can name the rule that explains it.
Starter
from enum import Enum, StrEnum, auto
class Channel(StrEnum):
ONLINE = auto()
STORE = auto()
class Region(Enum):
NORTH = auto()
SOUTH = auto()
print(list(Channel))
print(Channel.ONLINE == "online", Region.NORTH == 1)
print(Region(2), Region["NORTH"].value)
print(f"{Channel.STORE}|{Region.SOUTH}")
print("store" in Channel, len(Region))
Hint 1

auto() gives the lowercase name in a StrEnum, and 1, 2, 3 in a plain Enum.

Hint 2

A StrEnum member is a string. A plain Enum member is not equal to its value.

Solution
from enum import Enum, StrEnum, auto
class Channel(StrEnum):
ONLINE = auto()
STORE = auto()
class Region(Enum):
NORTH = auto()
SOUTH = auto()
print(list(Channel))
print(Channel.ONLINE == "online", Region.NORTH == 1)
print(Region(2), Region["NORTH"].value)
print(f"{Channel.STORE}|{Region.SOUTH}")
print("store" in Channel, len(Region))
assert Region(1) is Region.NORTH
Output
[<Channel.ONLINE: 'online'>, <Channel.STORE: 'store'>]
True False
Region.SOUTH 1
store|Region.SOUTH
True 2

How it works:

  1. Line 1: a list shows the repr of each member, with the values that auto() chose.
  2. Line 2: the StrEnum member equals its string. The plain Enum member does not equal its integer value.
  3. Line 3: Region(2) looks up by value and prints as Region.SOUTH. Region["NORTH"] looks up by name; its value is 1.
  4. Line 4: in an f-string, the StrEnum member shows its value, the plain member shows Class.NAME.
  5. Line 5: since Python 3.12, in accepts a value. The enum has two members.
Warm-up

Define Store as a typing.NamedTuple with store_id, city, region and size_sqm (an int). Build one Store per row of data/stores.csv. Print the first store, unpack the largest store into four names and print them, and make a copy of the first store with a new size with _replace().

Expected output
Store(store_id='S01', city='Chicago', region='North', size_sqm=2850)
largest: S07 New York (East) 3,400 m²
Store(store_id='S01', city='Chicago', region='North', size_sqm=3000)
Starter
from typing import NamedTuple
class Store(NamedTuple):
store_id: str
# TODO: city, region, size_sqm
rows = read_csv("data/stores.csv")
# TODO: stores = [...] with size_sqm converted to int
# TODO: print stores[0]
# TODO: find the largest store with max(..., key=...) and unpack it
# TODO: print a copy of stores[0] with size_sqm=3000
Hint 1

Store(row["store_id"], row["city"], row["region"], int(row["size_sqm"])) builds one store.

Hint 2

max(stores, key=lambda s: s.size_sqm) compares by size. Then store_id, city, region, size = largest.

Solution
from typing import NamedTuple
class Store(NamedTuple):
store_id: str
city: str
region: str
size_sqm: int
rows = read_csv("data/stores.csv")
stores = [
Store(row["store_id"], row["city"], row["region"], int(row["size_sqm"]))
for row in rows
]
print(stores[0])
largest = max(stores, key=lambda s: s.size_sqm)
store_id, city, region, size = largest
print(f"largest: {store_id} {city} ({region}) {size:,} m²")
print(stores[0]._replace(size_sqm=3000))
assert len(stores) == 12 and largest.store_id == "S07"
assert stores[0].size_sqm == 2850 # _replace made a copy
Output
Store(store_id='S01', city='Chicago', region='North', size_sqm=2850)
largest: S07 New York (East) 3,400 m²
Store(store_id='S01', city='Chicago', region='North', size_sqm=3000)

How it works:

  1. A named tuple has a field name for each position. largest.size_sqm and largest[3] are the same value.
  2. key=lambda s: s.size_sqm is needed: without it, max() would compare the tuples from the first field, the store id.
  3. A named tuple unpacks like any tuple.
  4. Named tuples are immutable. _replace() returns a new tuple and leaves stores[0] unchanged.

Alternative: Store._make(...) builds a store from any iterable of four values, and operator.attrgetter("size_sqm") can replace the lambda.

M21-W08 · Fix the attributes of a point with slots

Section titled “M21-W08 · Fix the attributes of a point with slots”
Warm-up

A KNN training set holds many labelled points. Write a class LabelledPoint with __slots__ for x, y and label, and an __init__ that sets them. Create one point, show that it has no __dict__, and catch the AttributeError from a misspelled attribute lable.

Expected output
('x', 'y', 'label') False
'LabelledPoint' object has no attribute 'lable' and no __dict__ for setting new attributes
label is still 1
Starter
class LabelledPoint:
# TODO: __slots__ and __init__
...
point = LabelledPoint(6.0, 2.0, 1) # tenure_months, logins_last_30d, churned
# TODO: print the slots and hasattr(point, "__dict__")
# TODO: try point.lable = 0 and print the error message
# TODO: print the label
Hint 1

__slots__ = ("x", "y", "label") goes in the class body, before __init__.

Hint 2

Wrap the assignment in try: / except AttributeError as exc: and print exc.

Solution
class LabelledPoint:
__slots__ = ("x", "y", "label")
def __init__(self, x: float, y: float, label: int) -> None:
self.x = x
self.y = y
self.label = label
point = LabelledPoint(6.0, 2.0, 1) # tenure_months, logins_last_30d, churned
print(LabelledPoint.__slots__, hasattr(point, "__dict__"))
try:
point.lable = 0
except AttributeError as exc:
print(exc)
print("label is still", point.label)
assert not hasattr(point, "__dict__")
Output
('x', 'y', 'label') False
'LabelledPoint' object has no attribute 'lable' and no __dict__ for setting new attributes
label is still 1

How it works:

  1. __slots__ lists the only attribute names an instance can have. Python reserves one slot per name and creates no __dict__.
  2. The typo lable is not a slot, so the assignment fails instead of adding a new attribute.
  3. The real label keeps its value. Slots fix the names, not the values.

Alternative: @dataclass(slots=True) with three annotated fields writes __slots__, __init__ and __repr__ for you.

M21-C01 · Validate customer records in post_init

Section titled “M21-C01 · Validate customer records in post_init”
Core

Write a dataclass Customer with customer_id: str, age: int, tenure_months: int and churned: bool, and a class method from_row(row) that converts the text of one CSV row. __post_init__ must reject an id that is not C plus 5 digits, an age outside 18–80 and a negative tenure, each with a clear ValueError. Load all rows of data/customers.csv, then try the three bad rows of the starter and print each error.

Expected output
5000 Customer(customer_id='C00001', age=18, tenure_months=72, churned=False)
churned: 963
rejected: bad customer_id 'C1'
rejected: C00042: age 17 outside 18-80
rejected: C00043: negative tenure -2
Starter
from dataclasses import dataclass
from typing import Self
@dataclass
class Customer:
customer_id: str
age: int
tenure_months: int
churned: bool
# TODO: __post_init__ with three checks
# TODO: from_row(cls, row) as a @classmethod
customers = [Customer.from_row(row) for row in read_csv("data/customers.csv")]
# TODO: print the number of customers, the first one and the churn count
bad_rows = [
{"customer_id": "C1", "age": "40", "tenure_months": "3", "churned": "0"},
{"customer_id": "C00042", "age": "17", "tenure_months": "3", "churned": "0"},
{"customer_id": "C00043", "age": "30", "tenure_months": "-2", "churned": "1"},
]
# TODO: try each bad row and print the error
Hint 1

The id check: len(self.customer_id) == 6 and self.customer_id[0] == "C" and self.customer_id[1:].isdigit().

Hint 2

from_row returns cls(row["customer_id"], int(row["age"]), int(row["tenure_months"]), row["churned"] == "1"). Do not use bool("0"): it is True.

Solution
from dataclasses import dataclass
from typing import Self
@dataclass
class Customer:
customer_id: str
age: int
tenure_months: int
churned: bool
def __post_init__(self) -> None:
cid = self.customer_id
if not (len(cid) == 6 and cid[0] == "C" and cid[1:].isdigit()):
raise ValueError(f"bad customer_id {cid!r}")
if not 18 <= self.age <= 80:
raise ValueError(f"{cid}: age {self.age} outside 18-80")
if self.tenure_months < 0:
raise ValueError(f"{cid}: negative tenure {self.tenure_months}")
@classmethod
def from_row(cls, row: dict[str, str]) -> Self:
return cls(
row["customer_id"],
int(row["age"]),
int(row["tenure_months"]),
row["churned"] == "1",
)
customers = [Customer.from_row(row) for row in read_csv("data/customers.csv")]
print(len(customers), customers[0])
print("churned:", sum(c.churned for c in customers))
bad_rows = [
{"customer_id": "C1", "age": "40", "tenure_months": "3", "churned": "0"},
{"customer_id": "C00042", "age": "17", "tenure_months": "3", "churned": "0"},
{"customer_id": "C00043", "age": "30", "tenure_months": "-2", "churned": "1"},
]
for row in bad_rows:
try:
Customer.from_row(row)
except ValueError as exc:
print("rejected:", exc)
assert len(customers) == 5000
assert sum(c.churned for c in customers) == 963
Output
5000 Customer(customer_id='C00001', age=18, tenure_months=72, churned=False)
churned: 963
rejected: bad customer_id 'C1'
rejected: C00042: age 17 outside 18-80
rejected: C00043: negative tenure -2

How it works:

  1. from_row converts text to the field types. The class method is the alternative constructor of module 18.
  2. The generated __init__ stores the values and then calls __post_init__, so every way of creating a Customer runs the checks.
  3. True counts as 1 in sum(), so sum(c.churned ...) counts the churners: 963, as in the data dictionary.

Alternative: collect all problems of one record in a list and raise one error with all of them. A user who fixes a file by hand then sees every problem at once.

M21-C02 · Compute a derived revenue field

Section titled “M21-C02 · Compute a derived revenue field”
Core

Each line of data/sales.csv has unit_price, quantity, discount and revenue. Write a frozen dataclass OrderLine with order_id, unit_price, quantity, discount and a derived field revenue that __post_init__ computes as round(unit_price * quantity * (1 - discount), 2). Build the first 1,000 lines and print the first one. Count the lines whose computed revenue differs from the file, print the largest difference and the total revenue.

Expected output
OrderLine(order_id='O000001', unit_price=69.99, quantity=1, discount=0.05, revenue=66.49)
lines that differ: 9, largest difference: 0.01 USD
total revenue: 178,725.93 USD
Starter
from dataclasses import dataclass, field
@dataclass(frozen=True)
class OrderLine:
order_id: str
unit_price: float
quantity: int
discount: float
revenue: float = field(init=False)
def __post_init__(self) -> None:
# TODO: compute revenue; remember that the class is frozen
...
rows = read_csv("data/sales.csv")[:1000]
# TODO: build the lines, print the first
# TODO: count the differences, print the largest one and the total
Hint 1

self.revenue = ... raises FrozenInstanceError in a frozen class. Use object.__setattr__(self, "revenue", value).

Hint 2

Pair each line with its row with zip(lines, rows, strict=True) and compute abs(line.revenue - float(row["revenue"])). A line differs when this gap is above 1e-9.

Solution
from dataclasses import dataclass, field
@dataclass(frozen=True)
class OrderLine:
order_id: str
unit_price: float
quantity: int
discount: float
revenue: float = field(init=False)
def __post_init__(self) -> None:
value = round(self.unit_price * self.quantity * (1 - self.discount), 2)
object.__setattr__(self, "revenue", value)
rows = read_csv("data/sales.csv")[:1000]
lines = [
OrderLine(
r["order_id"], float(r["unit_price"]), int(r["quantity"]), float(r["discount"])
)
for r in rows
]
print(lines[0])
pairs = zip(lines, rows, strict=True)
gaps = [abs(line.revenue - float(row["revenue"])) for line, row in pairs]
differ = sum(gap > 1e-9 for gap in gaps)
total = sum(line.revenue for line in lines)
print(f"lines that differ: {differ}, largest difference: {max(gaps):.2f} USD")
print(f"total revenue: {total:,.2f} USD")
assert max(gaps) < 0.0101 # never more than one cent
assert lines[0].revenue == 66.49
Output
OrderLine(order_id='O000001', unit_price=69.99, quantity=1, discount=0.05, revenue=66.49)
lines that differ: 9, largest difference: 0.01 USD
total revenue: 178,725.93 USD

How it works:

  1. field(init=False) keeps revenue out of __init__, so a caller cannot pass a wrong value.
  2. object.__setattr__ sets the field once, while the frozen object is being built.
  3. The revenue is a field, so it appears in the repr and takes part in == and the hash.
  4. Nine lines differ by exactly one cent. The file was rounded with NumPy, and a value such as 2.675 is stored as 2.67499… in binary, so the two roundings can land on different cents (module 01). For money, compare with a tolerance of one cent, or compute in whole cents.

Alternative: a @property named revenue computes the value on each read and stores nothing. It does not appear in the repr or in asdict(), which matters if you export the lines.

M21-C03 · Rank cross-validation results with order=True

Section titled “M21-C03 · Rank cross-validation results with order=True”
Core

The data dictionary lists the mean 5-fold ROC-AUC of three churn models: LogisticRegression 0.814, HistGradientBoosting 0.831 and HistGradientBoosting (tuned) 0.847. Add a "DummyClassifier" at 0.5. Write a frozen dataclass CVResult with order=True, fields mean_auc and model, where only mean_auc takes part in comparisons. Print a ranked table, best first, and the name of the best model.

Expected output
1. HistGradientBoosting (tuned) 0.847
2. HistGradientBoosting 0.831
3. LogisticRegression 0.814
4. DummyClassifier 0.500
best: HistGradientBoosting (tuned)
Starter
from dataclasses import dataclass, field
@dataclass(frozen=True, order=True)
class CVResult:
# TODO: mean_auc first; model excluded from comparisons
...
results = [
# TODO: four CVResult objects
]
# TODO: print rank, model and score, best first; then the best model's name
Hint 1

The order methods compare the fields in class order. Put mean_auc first.

Hint 2

model: str = field(compare=False). Then sorted(results, reverse=True) and enumerate(..., start=1).

Solution
from dataclasses import dataclass, field
@dataclass(frozen=True, order=True)
class CVResult:
mean_auc: float
model: str = field(compare=False)
results = [
CVResult(0.814, "LogisticRegression"),
CVResult(0.831, "HistGradientBoosting"),
CVResult(0.847, "HistGradientBoosting (tuned)"),
CVResult(0.5, "DummyClassifier"),
]
for rank, result in enumerate(sorted(results, reverse=True), start=1):
print(f"{rank}. {result.model:<30} {result.mean_auc:.3f}")
print("best:", max(results).model)
assert max(results).mean_auc == 0.847
assert CVResult(0.5, "a") == CVResult(0.5, "b") # the model name is not compared
Output
1. HistGradientBoosting (tuned) 0.847
2. HistGradientBoosting 0.831
3. LogisticRegression 0.814
4. DummyClassifier 0.500
best: HistGradientBoosting (tuned)

How it works:

  1. order=True generates <, <=, >, >= from the tuple of compared fields, here only (mean_auc,).
  2. sorted(..., reverse=True) and max() use those methods.
  3. compare=False also removes model from ==: two results with the same score are equal, as the last assert shows. Keep that in mind before you put results in a set.

Alternative: skip order=True and sort with a key: sorted(results, key=lambda r: r.mean_auc, reverse=True). A key keeps == meaning “all fields equal” and lets you sort by other fields elsewhere.

M21-C04 · Refactor a hand-written class into a dataclass

Section titled “M21-C04 · Refactor a hand-written class into a dataclass”
Core

Refactor: the starter has a hand-written SensorSummary with __init__, __repr__ and __eq__. Replace it with a dataclass that behaves the same, then build one summary per sensor of data/sensors.csv (number of temperature readings and their mean, skipping blanks, rounded to 2 decimals).

Expected output
SensorSummary(sensor_id='S1', n_readings=2010, mean_c=22.05)
SensorSummary(sensor_id='S2', n_readings=2012, mean_c=24.6)
SensorSummary(sensor_id='S3', n_readings=2010, mean_c=23.53)
SensorSummary(sensor_id='S4', n_readings=2010, mean_c=26.04)
True
Starter
class SensorSummary:
def __init__(self, sensor_id: str, n_readings: int, mean_c: float) -> None:
self.sensor_id = sensor_id
self.n_readings = n_readings
self.mean_c = mean_c
def __repr__(self) -> str:
return (
f"SensorSummary(sensor_id={self.sensor_id!r}, "
f"n_readings={self.n_readings!r}, mean_c={self.mean_c!r})"
)
def __eq__(self, other: object) -> bool:
if not isinstance(other, SensorSummary):
return NotImplemented
return (self.sensor_id, self.n_readings, self.mean_c) == (
other.sensor_id, other.n_readings, other.mean_c
)
# TODO: replace the class above with a dataclass
# TODO: group the non-blank temperatures by sensor and print one summary per sensor
# TODO: compare the first summary with SensorSummary("S1", 2010, 22.05)
Hint 1

The three annotated fields in the same order give the same __init__, __repr__ and __eq__.

Hint 2

Group with defaultdict(list): temps[row["sensor_id"]].append(float(row["temperature_c"])) when the cell is not empty.

Solution
import statistics
from collections import defaultdict
from dataclasses import dataclass
@dataclass
class SensorSummary:
sensor_id: str
n_readings: int
mean_c: float
temps: defaultdict[str, list[float]] = defaultdict(list)
for row in read_csv("data/sensors.csv"):
if row["temperature_c"]:
temps[row["sensor_id"]].append(float(row["temperature_c"]))
summaries = [
SensorSummary(sensor, len(values), round(statistics.fmean(values), 2))
for sensor, values in sorted(temps.items())
]
for summary in summaries:
print(summary)
print(summaries[0] == SensorSummary("S1", 2010, 22.05))
assert [s.sensor_id for s in summaries] == ["S1", "S2", "S3", "S4"]
assert sum(s.n_readings for s in summaries) == 8064 - 22
Output
SensorSummary(sensor_id='S1', n_readings=2010, mean_c=22.05)
SensorSummary(sensor_id='S2', n_readings=2012, mean_c=24.6)
SensorSummary(sensor_id='S3', n_readings=2010, mean_c=23.53)
SensorSummary(sensor_id='S4', n_readings=2010, mean_c=26.04)
True

How it works:

  1. The dataclass generates the same three methods from three lines. The repr text is identical to the hand-written one.
  2. 22 temperature cells are blank, so the counts add up to 8,042.
  3. The means match the data dictionary: S1 22.05, S2 24.60, S3 23.53, S4 26.04.

Alternative: keep a hand-written __repr__ only when you want a different text, for example S1: 22.05 °C (2,010 readings). @dataclass does not replace a __repr__ that the class defines.

M21-C05 · Save nested dataclasses as JSON and load them back

Section titled “M21-C05 · Save nested dataclasses as JSON and load them back”
Core

An Experiment has a name, a nested frozen TrainConfig (learning_rate=0.01, epochs=100) and a list of scores. Convert an experiment to JSON with asdict(), change the list inside the dict to prove that asdict() copied it, and rebuild an equal experiment from the JSON text with a class method from_dict.

Expected output
{"name": "knn-k15", "config": {"learning_rate": 0.01, "epochs": 20}, "scores": [0.81, 0.83]}
[0.81, 0.83]
Experiment(name='knn-k15', config=TrainConfig(learning_rate=0.01, epochs=20), scores=[0.81, 0.83])
True False
Starter
import json
from dataclasses import asdict, dataclass, field
from typing import Any, Self
@dataclass(frozen=True)
class TrainConfig:
learning_rate: float = 0.01
epochs: int = 100
@dataclass
class Experiment:
name: str
config: TrainConfig
scores: list[float] = field(default_factory=list)
# TODO: from_dict(cls, data) that rebuilds the nested TrainConfig
exp = Experiment("knn-k15", TrainConfig(epochs=20), [0.81, 0.83])
# TODO: d = asdict(exp); print the JSON text
# TODO: append to d["scores"]; print exp.scores
# TODO: rebuild from the JSON text; print it and whether it equals exp
Hint 1

asdict() turns the nested dataclass into a nested dict. json.dumps(d) then writes it.

Hint 2

from_dict must call TrainConfig(**data["config"]) itself: JSON has no idea of your classes.

Solution
import json
from dataclasses import asdict, dataclass, field
from typing import Any, Self
@dataclass(frozen=True)
class TrainConfig:
learning_rate: float = 0.01
epochs: int = 100
@dataclass
class Experiment:
name: str
config: TrainConfig
scores: list[float] = field(default_factory=list)
@classmethod
def from_dict(cls, data: dict[str, Any]) -> Self:
return cls(data["name"], TrainConfig(**data["config"]), list(data["scores"]))
exp = Experiment("knn-k15", TrainConfig(epochs=20), [0.81, 0.83])
d = asdict(exp)
text = json.dumps(d)
print(text)
d["scores"].append(0.99)
print(exp.scores)
rebuilt = Experiment.from_dict(json.loads(text))
print(rebuilt)
print(rebuilt == exp, rebuilt.config is exp.config)
assert rebuilt == exp
assert exp.scores == [0.81, 0.83]
Output
{"name": "knn-k15", "config": {"learning_rate": 0.01, "epochs": 20}, "scores": [0.81, 0.83]}
[0.81, 0.83]
Experiment(name='knn-k15', config=TrainConfig(learning_rate=0.01, epochs=20), scores=[0.81, 0.83])
True False

How it works:

  1. asdict() works recursively: the nested TrainConfig becomes a nested dict, and the list is copied.
  2. Appending to d["scores"] does not touch exp.scores: asdict() shares no mutable data with the object.
  3. from_dict rebuilds the nested object. The two experiments are equal, field by field, also inside the config, but they are new objects.

Alternative: for many nested classes, a library such as pydantic (module 44) rebuilds nested objects from JSON for you, with type checks.

M21-C06 · Churn rate by payment method with a StrEnum

Section titled “M21-C06 · Churn rate by payment method with a StrEnum”
Core

The payment_method column of data/customers.csv has four values: electronic_check, credit_card, bank_transfer and paypal. Define a StrEnum PaymentMethod with auto() values in that order. Convert the column, and print the number of customers and the churn rate per method in enum order. Then print the method with the highest churn rate.

Expected output
electronic_check 1,563 churn 24.8%
credit_card 1,360 churn 15.8%
bank_transfer 1,209 churn 17.4%
paypal 868 churn 17.4%
highest churn: ELECTRONIC_CHECK
Starter
from collections import Counter
from enum import StrEnum, auto
class PaymentMethod(StrEnum):
# TODO: four members with auto()
...
rows = read_csv("data/customers.csv")
# TODO: count customers and churners per method
# TODO: print the table in enum order and the method with the highest rate
Hint 1

auto() in a StrEnum gives the lowercase member name: ELECTRONIC_CHECK = auto() has the value "electronic_check", which is exactly the text in the file.

Hint 2

Build a dict rate = {m: lost[m] / total[m] for m in PaymentMethod} and use max(rate, key=rate.get).

Solution
from collections import Counter
from enum import StrEnum, auto
class PaymentMethod(StrEnum):
ELECTRONIC_CHECK = auto()
CREDIT_CARD = auto()
BANK_TRANSFER = auto()
PAYPAL = auto()
rows = read_csv("data/customers.csv")
methods = [PaymentMethod(row["payment_method"]) for row in rows]
total = Counter(methods)
lost = Counter(m for m, row in zip(methods, rows, strict=True) if row["churned"] == "1")
rate = {m: lost[m] / total[m] for m in PaymentMethod}
for method in PaymentMethod:
print(f"{method:<17} {total[method]:>5,} churn {rate[method]:.1%}")
worst = max(rate, key=rate.get)
print("highest churn:", worst.name)
assert sum(total.values()) == 5000
assert worst is PaymentMethod.ELECTRONIC_CHECK
Output
electronic_check 1,563 churn 24.8%
credit_card 1,360 churn 15.8%
bank_transfer 1,209 churn 17.4%
paypal 868 churn 17.4%
highest churn: ELECTRONIC_CHECK

How it works:

  1. The member names are the file values in upper case, so auto() produces exactly the values in the file.
  2. PaymentMethod(...) rejects any other text, so a new method in next month’s export would stop the script instead of vanishing from the report.
  3. max(rate, key=rate.get) returns the key with the largest value, a member. Electronic checks churn most (24.8%); they rarely come with autopay.

Alternative: sorted(rate.items(), key=lambda kv: kv[1], reverse=True) prints the table sorted by churn rate instead of in enum order.

M21-C07 · Find the worst status per sensor with an IntEnum

Section titled “M21-C07 · Find the worst status per sensor with an IntEnum”
Core

Severity levels have an order: ok < warn < fail. Define Severity(IntEnum) with OK = 0, WARN = 1 and FAIL = 2. Convert the status column of data/sensors.csv with a lookup by name. For each sensor, print the worst severity and the number of readings that are not OK.

Expected output
S1: worst WARN alerts 14
S2: worst FAIL alerts 22
S3: worst WARN alerts 22
S4: worst FAIL alerts 419
Starter
from collections import defaultdict
from enum import IntEnum
class Severity(IntEnum):
# TODO: OK, WARN, FAIL with 0, 1, 2
...
rows = read_csv("data/sensors.csv")
# TODO: group the severities by sensor_id
# TODO: print sensor, worst severity name and the count of readings above OK
Hint 1

The file says warn, the member name is WARN: Severity[row["status"].upper()].

Hint 2

IntEnum members are ordered, so max(levels) gives the worst one and level > Severity.OK works.

Solution
from collections import defaultdict
from enum import IntEnum
class Severity(IntEnum):
OK = 0
WARN = 1
FAIL = 2
rows = read_csv("data/sensors.csv")
levels: defaultdict[str, list[Severity]] = defaultdict(list)
for row in rows:
levels[row["sensor_id"]].append(Severity[row["status"].upper()])
for sensor, values in sorted(levels.items()):
worst = max(values)
alerts = sum(level > Severity.OK for level in values)
print(f"{sensor}: worst {worst.name:<4} alerts {alerts:>3}")
assert max(levels["S4"]) is Severity.FAIL
assert sum(v == Severity.FAIL for v in levels["S2"]) == 5
Output
S1: worst WARN alerts 14
S2: worst FAIL alerts 22
S3: worst WARN alerts 22
S4: worst FAIL alerts 419

How it works:

  1. Severity[...] looks up by name. .upper() turns the file value into the name.
  2. IntEnum members compare as ints, so max() returns the worst level. A plain Enum would raise TypeError on <.
  3. max() returns a member, so .name gives FAIL and not 2.
  4. S4 has 400 warnings and 19 failures, the wear that starts on May 12.

Alternative: keep a plain Enum with the values "ok", "warn", "fail" and a dict RANK = {Status.OK: 0, ...}, then max(values, key=RANK.get). This keeps the members from being mixed up with ints.

M21-C08 · Choose an aggregation with an Enum and match

Section titled “M21-C08 · Choose an aggregation with an Enum and match”
Core

A dashboard lets the user choose how to aggregate the temperatures of each sensor: mean, median or max. Define Aggregation(StrEnum) and a function aggregate(values, how) that uses match on the member. Parse the settings ["mean", "max"] and print one line per setting with the value of each sensor, rounded to 2 decimals.

Expected output
mean S1=22.05 S2=24.60 S3=23.53 S4=26.04
max S1=38.63 S2=44.89 S3=41.66 S4=44.36
Starter
import statistics
from collections import defaultdict
from enum import StrEnum, auto
class Aggregation(StrEnum):
MEAN = auto()
# TODO: MEDIAN, MAX
def aggregate(values: list[float], how: Aggregation) -> float:
# TODO: match how with dotted value patterns and a final case _
...
temps: defaultdict[str, list[float]] = defaultdict(list)
# TODO: fill temps from data/sensors.csv, skipping blank cells
# TODO: for each setting in ["mean", "max"], print the setting and the four values
Hint 1

Write case Aggregation.MEAN:, with the class name. A bare case MEAN: would capture everything.

Hint 2

statistics.fmean, statistics.median and max do the three jobs.

Solution
import statistics
from collections import defaultdict
from enum import StrEnum, auto
class Aggregation(StrEnum):
MEAN = auto()
MEDIAN = auto()
MAX = auto()
def aggregate(values: list[float], how: Aggregation) -> float:
match how:
case Aggregation.MEAN:
return statistics.fmean(values)
case Aggregation.MEDIAN:
return statistics.median(values)
case Aggregation.MAX:
return max(values)
case _:
raise ValueError(f"unsupported aggregation {how!r}")
temps: defaultdict[str, list[float]] = defaultdict(list)
for row in read_csv("data/sensors.csv"):
if row["temperature_c"]:
temps[row["sensor_id"]].append(float(row["temperature_c"]))
for setting in ["mean", "max"]:
how = Aggregation(setting)
parts = [f"{s}={aggregate(v, how):.2f}" for s, v in sorted(temps.items())]
print(f"{how:<6}", " ".join(parts))
assert round(aggregate(temps["S4"], Aggregation.MEAN), 2) == 26.04
Output
mean S1=22.05 S2=24.60 S3=23.53 S4=26.04
max S1=38.63 S2=44.89 S3=41.66 S4=44.36

How it works:

  1. Aggregation(setting) turns the user’s text into a member, or raises ValueError for anything else.
  2. The match lists one formula per member with dotted value patterns. case _ catches a member that someone adds later without a formula.
  3. The maxima are far above the means: they are the temperature spikes of the sensor data (+9 to +18 °C).

Alternative: a dict that maps each member to a function, {Aggregation.MEAN: statistics.fmean, ...}, replaces the match. Module 22 calls this the strategy pattern.

M21-C09 · Fix the bug: the match that matches everything

Section titled “M21-C09 · Fix the bug: the match that matches everything”
Core

Fix the bug: this function should describe each distance metric. It prints a wrong description for CHEBYSHEV, and no error tells you. Find the cause, fix the match, and make an unhandled member raise ValueError.

Expected output
EUCLIDEAN square root of the sum of squared differences
MANHATTAN sum of absolute differences
CHEBYSHEV largest absolute difference
Starter
from enum import Enum
class Distance(Enum):
EUCLIDEAN = "euclidean"
MANHATTAN = "manhattan"
CHEBYSHEV = "chebyshev"
def describe(metric: Distance) -> str:
match metric:
case Distance.EUCLIDEAN:
return "square root of the sum of squared differences"
case MANHATTAN:
return "sum of absolute differences"
# TODO: fix the match; add CHEBYSHEV ("largest absolute difference")
for d in Distance:
print(f"{d.name:<10} {describe(d)}")
Hint 1

Is MANHATTAN in the second case a member of the enum, or a new name?

Hint 2

A bare name in a pattern is a capture pattern. It matches any value. Write case Distance.MANHATTAN:.

Solution
from enum import Enum
class Distance(Enum):
EUCLIDEAN = "euclidean"
MANHATTAN = "manhattan"
CHEBYSHEV = "chebyshev"
def describe(metric: Distance) -> str:
match metric:
case Distance.EUCLIDEAN:
return "square root of the sum of squared differences"
case Distance.MANHATTAN:
return "sum of absolute differences"
case Distance.CHEBYSHEV:
return "largest absolute difference"
case _:
raise ValueError(f"no description for {metric!r}")
for d in Distance:
print(f"{d.name:<10} {describe(d)}")
assert describe(Distance.CHEBYSHEV).startswith("largest")
Output
EUCLIDEAN square root of the sum of squared differences
MANHATTAN sum of absolute differences
CHEBYSHEV largest absolute difference

How it works:

  1. In the starter, case MANHATTAN: is a capture pattern: it binds any subject to a new local name MANHATTAN. As the last case, it is allowed, and it matched CHEBYSHEV.
  2. Dotted names such as Distance.MANHATTAN are value patterns. They compare with ==.
  3. The final case _ raises for a member that has no description, so the next forgotten case fails loudly.

Alternative: give the enum a property description with the same match on self, as Example 4 of the lesson does with between(). The text then travels with the member.

M21-C10 · Fix the bug: comparable houses sorted by id

Section titled “M21-C10 · Fix the bug: comparable houses sorted by id”
Core

Fix the bug: a real-estate tool finds the 3 Riverside houses in data/houses.csv whose size is closest to 1,835 sqft (the “comparables”) and reports their median price. The starter returns the wrong houses: they are the first three ids, not the closest. Fix it, and break ties in size by the house id.

Expected output
Comp(house_id='H0461', sqft_gap=5, price=423500)
Comp(house_id='H0999', sqft_gap=5, price=377500)
Comp(house_id='H2804', sqft_gap=5, price=712500)
median price: 423500
Starter
import statistics
from typing import NamedTuple
class Comp(NamedTuple):
house_id: str
sqft_gap: int
price: int
target_sqft = 1835
comps = [
Comp(r["house_id"], abs(int(r["sqft"]) - target_sqft), int(r["price"]))
for r in read_csv("data/houses.csv")
if r["neighborhood"] == "Riverside"
]
closest = sorted(comps)[:3] # TODO: this sorts by the wrong field
for comp in closest:
print(comp)
print("median price:", statistics.median(c.price for c in closest))
Hint 1

How does Python compare two tuples? Which field of Comp comes first?

Hint 2

Pass a key: sorted(comps, key=lambda c: (c.sqft_gap, c.house_id)).

Solution
import statistics
from typing import NamedTuple
class Comp(NamedTuple):
house_id: str
sqft_gap: int
price: int
target_sqft = 1835
comps = [
Comp(r["house_id"], abs(int(r["sqft"]) - target_sqft), int(r["price"]))
for r in read_csv("data/houses.csv")
if r["neighborhood"] == "Riverside"
]
closest = sorted(comps, key=lambda c: (c.sqft_gap, c.house_id))[:3]
for comp in closest:
print(comp)
print("median price:", statistics.median(c.price for c in closest))
assert all(c.sqft_gap <= closest[-1].sqft_gap for c in closest)
assert len(comps) == 370
Output
Comp(house_id='H0461', sqft_gap=5, price=423500)
Comp(house_id='H0999', sqft_gap=5, price=377500)
Comp(house_id='H2804', sqft_gap=5, price=712500)
median price: 423500

How it works:

  1. A named tuple sorts as a tuple: by its first field, then the second. For Comp, that is house_id, so the starter returned the three smallest ids.
  2. The key (c.sqft_gap, c.house_id) sorts by size gap and breaks ties by id, so the result is the same on every run.
  3. The median of three prices is the middle one: a robust estimate that one odd sale cannot move far.

Alternative: put sqft_gap first in the class, so the natural order is right. A key is clearer, because it states the sort order where you sort, and it survives a change of the field order.

Core

Choose a method and justify it: for each scenario, pick one of dict, TypedDict, NamedTuple, dataclass, frozen dataclass, slotted dataclass, plain class or pydantic model. Store your choices in a dict, print them, and write one sentence of justification for each before you open the solution.

  1. The parsed data/config.json that a training script passes to ten functions. No code may change it.
  2. The JSON body of a POST /predict request from a public web form.
  3. 10 million sensor readings kept in memory by a monitoring job. The values are updated in place when a correction arrives.
  4. A KNNClassifier with fit(), predict() and learned attributes.
  5. Type hints for the records of data/customers.json, which the code loads and passes on unchanged.
  6. A function that returns (mean, std). Old code unpacks the result as a pair.
Expected output
1. frozen dataclass
2. pydantic model
3. slotted dataclass
4. plain class
5. TypedDict
6. NamedTuple
Starter
choices = {
1: "...", # TODO: one choice per scenario
}
for number, choice in choices.items():
print(f"{number}. {choice}")
Hint 1

Ask the questions of the lesson’s flowchart: does it mainly hold data? Is the input untrusted? Must it unpack like a tuple? Must it be immutable? Are there millions of them?

Hint 2

Scenario 3 must stay mutable, so NamedTuple and frozen classes are out. Scenario 6 must keep working with mean, std = result.

Solution
choices = {
1: "frozen dataclass",
2: "pydantic model",
3: "slotted dataclass",
4: "plain class",
5: "TypedDict",
6: "NamedTuple",
}
for number, choice in choices.items():
print(f"{number}. {choice}")
assert len(set(choices.values())) == 6
Output
1. frozen dataclass
2. pydantic model
3. slotted dataclass
4. plain class
5. TypedDict
6. NamedTuple

How it works:

  1. Config: a frozen dataclass validates in __post_init__, names every setting and blocks changes. Ten functions can share it safely.
  2. Web request: the input is untrusted. A pydantic model checks and converts every field and returns clear errors (module 44).
  3. 10 million readings: slots=True cuts the memory per object, and the instances stay mutable for corrections. A NamedTuple is small too, but it is immutable.
  4. Estimator: it has behavior and state that changes during fit(). A plain class (on BaseEstimator) fits. Its parameters are stored unchanged, as scikit-learn expects.
  5. JSON records passed on: a TypedDict adds type hints with no conversion and no copy. The values stay plain dicts, which is what the next function expects.
  6. (mean, std): a NamedTuple keeps mean, std = result working and adds result.mean.

Alternative: for scenario 1, a slots=True, frozen=True dataclass is also a good answer. For scenario 3, at 10 million rows, a NumPy array or a DataFrame column (module 23) beats any per-object design by a wide margin.

M21-C12 · Interpret a memory measurement: strings vs enum members

Section titled “M21-C12 · Interpret a memory measurement: strings vs enum members”
Core

Interpret a result: csv.DictReader creates a new string object for every cell. Load the plan column of data/customers.csv twice, once as strings and once as Plan members (a StrEnum with BASIC, STANDARD, PREMIUM), and measure with tracemalloc how much memory each list keeps. Print the bytes per row and explain the difference.

Expected output
str 57.0 bytes per row
Plan 8.6 bytes per row
['premium', 'standard'] [<Plan.PREMIUM: 'premium'>, <Plan.STANDARD: 'standard'>]
True 3
Starter
import csv
import tracemalloc
from collections.abc import Callable
from enum import StrEnum, auto
class Plan(StrEnum):
BASIC = auto()
STANDARD = auto()
PREMIUM = auto()
def load_plans(convert: Callable[[str], object]) -> tuple[list[object], int]:
tracemalloc.start()
# TODO: read data/customers.csv and build [convert(row["plan"]) for row in ...]
# TODO: get the current traced memory, stop tracing, return (plans, used)
...
# TODO: measure str and Plan, print the bytes per row
Hint 1

used, _peak = tracemalloc.get_traced_memory() gives the bytes still allocated since start(). Read the file inside the measured part, and close it before you measure.

Hint 2

str and Plan are both callables that take one string: pass them as convert.

Solution
import csv
import tracemalloc
from collections.abc import Callable
from enum import StrEnum, auto
class Plan(StrEnum):
BASIC = auto()
STANDARD = auto()
PREMIUM = auto()
def load_plans(convert: Callable[[str], object]) -> tuple[list[object], int]:
tracemalloc.start()
with open("data/customers.csv", encoding="utf-8", newline="") as f:
plans = [convert(row["plan"]) for row in csv.DictReader(f)]
used, _peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return plans, used
as_text, text_bytes = load_plans(str)
as_enum, enum_bytes = load_plans(Plan)
print(f"str {text_bytes / len(as_text):5.1f} bytes per row")
print(f"Plan {enum_bytes / len(as_enum):5.1f} bytes per row")
print(as_text[:2], as_enum[:2])
print(as_text == as_enum, len({id(p) for p in as_enum}))
assert enum_bytes < text_bytes / 4
Output
str 57.0 bytes per row
Plan 8.6 bytes per row
['premium', 'standard'] [<Plan.PREMIUM: 'premium'>, <Plan.STANDARD: 'standard'>]
True 3

How it works:

  1. The string list keeps 5,000 separate string objects, one per row, plus the list: about 57 bytes per row.
  2. The enum list keeps only references to the same 3 member objects: one 8-byte pointer per row, plus the list’s spare capacity. Everything else that the CSV reader allocated was freed.
  3. str(row["plan"]) returns the same string object, so the string list really holds the strings that the reader created.
  4. StrEnum members equal their strings, so the two lists compare equal, and the enum version still works in string code.

Alternative: sys.intern(row["plan"]) also shares one object per distinct string, without an enum. The enum adds the validation: an unknown plan fails at load time.

M21-C13 · Fix the bug: a required field in a subclass

Section titled “M21-C13 · Fix the bug: a required field in a subclass”
Core

Fix the bug: KNNSpec adds a required field n_neighbors to ModelSpec, but the class definition fails with TypeError: non-default argument 'n_neighbors' follows default argument 'random_state'. Fix it without giving n_neighbors a default and without changing ModelSpec. Then show that a positional call is now rejected.

Expected output
KNNSpec(name='knn', random_state=42, n_neighbors=15)
TypeError: KNNSpec.__init__() takes from 2 to 3 positional arguments but 4 were given
Starter
from dataclasses import dataclass
@dataclass
class ModelSpec:
name: str
random_state: int = 42
@dataclass # TODO: fix this class
class KNNSpec(ModelSpec):
n_neighbors: int
spec = KNNSpec("knn", n_neighbors=15)
print(spec)
# TODO: try KNNSpec("knn", 7, 15) and print the error type and message
Hint 1

The generated __init__ lists the parent fields first. A required positional parameter cannot follow one with a default.

Hint 2

Keyword-only parameters do not follow that rule. @dataclass(kw_only=True) makes the fields of this class keyword-only.

Solution
from dataclasses import dataclass
@dataclass
class ModelSpec:
name: str
random_state: int = 42
@dataclass(kw_only=True)
class KNNSpec(ModelSpec):
n_neighbors: int
spec = KNNSpec("knn", n_neighbors=15)
print(spec)
try:
KNNSpec("knn", 7, 15)
except TypeError as exc:
print(f"{type(exc).__name__}: {exc}")
assert spec.random_state == 42 and spec.n_neighbors == 15
Output
KNNSpec(name='knn', random_state=42, n_neighbors=15)
TypeError: KNNSpec.__init__() takes from 2 to 3 positional arguments but 4 were given

How it works:

  1. kw_only=True applies to the fields defined in KNNSpec, not to the inherited ones. So name and random_state stay positional.
  2. A keyword-only parameter may come after parameters with defaults, so the class can be created.
  3. The call with three positional arguments fails: n_neighbors must be named. This makes calls readable.

Alternative: n_neighbors: int = field(kw_only=True) marks only this field. Or write _: KW_ONLY before it.

M21-X01 · Write a typed CSV loader for any dataclass

Section titled “M21-X01 · Write a typed CSV loader for any dataclass”
Challenge

Write load_records(path, cls) that reads a CSV and returns one cls instance per row. It must use dataclasses.fields(cls) to find the column names and each field’s type, and convert the text by type: bool ("1" is True), int, float, str, and any Enum subclass (lookup by value). Test it with a frozen, slotted CustomerRecord (customer_id, plan: Plan, contract: Contract, tenure_months: int, monthly_charges: float, churned: bool) and print the churn rate per plan and per contract, in enum order. An unknown enum value must raise a ValueError that lists the valid values: show it for the plan "gold".

Expected output
CustomerRecord(customer_id='C00001',
plan=<Plan.PREMIUM: 'premium'>,
contract=<Contract.TWO_YEAR: 'two-year'>,
tenure_months=72,
monthly_charges=84.69,
churned=False)
by plan:
basic 2,028 churn 17.4%
standard 1,982 churn 16.0%
premium 990 churn 29.6%
by contract:
month-to-month 2,784 churn 29.6%
one-year 1,225 churn 8.8%
two-year 991 churn 3.2%
'gold' is not a valid Plan; use one of: basic, standard, premium
Starter
import csv
from dataclasses import dataclass, fields
from enum import Enum, StrEnum, auto
from typing import Any
class Plan(StrEnum):
BASIC = auto()
STANDARD = auto()
PREMIUM = auto()
class Contract(StrEnum):
MONTH_TO_MONTH = "month-to-month"
ONE_YEAR = "one-year"
TWO_YEAR = "two-year"
@dataclass(frozen=True, slots=True)
class CustomerRecord:
customer_id: str
# TODO: plan, contract, tenure_months, monthly_charges, churned
def convert(text: str, kind: type) -> Any:
# TODO: bool, Enum subclasses, int, float, str
...
def load_records(path: str, cls: type) -> list:
# TODO: one cls(**kwargs) per row, using fields(cls)
...
def churn_by(records: list, attr: str, enum_cls: type[Enum]) -> None:
# TODO: print one line per member: value, count, churn rate
...
Hint 1

Each Field has .name and .type. Without from __future__ import annotations, .type is the real class, such as int or Plan.

Hint 2

Test bool before int, and test enums with isinstance(kind, type) and issubclass(kind, Enum). Any other type: call kind(text).

Hint 3

kwargs = {f.name: convert(row[f.name], f.type) for f in fields(cls)} ignores the CSV columns that are not fields.

Solution
import csv
from dataclasses import dataclass, fields
from enum import Enum, StrEnum, auto
from pprint import pprint
from typing import Any
class Plan(StrEnum):
BASIC = auto()
STANDARD = auto()
PREMIUM = auto()
class Contract(StrEnum):
MONTH_TO_MONTH = "month-to-month"
ONE_YEAR = "one-year"
TWO_YEAR = "two-year"
@dataclass(frozen=True, slots=True)
class CustomerRecord:
customer_id: str
plan: Plan
contract: Contract
tenure_months: int
monthly_charges: float
churned: bool
def convert(text: str, kind: type) -> Any:
if kind is bool:
return text == "1"
if isinstance(kind, type) and issubclass(kind, Enum):
try:
return kind(text)
except ValueError:
valid = ", ".join(str(m.value) for m in kind)
msg = f"{text!r} is not a valid {kind.__name__}; use one of: {valid}"
raise ValueError(msg) from None
return kind(text) # int, float, str and any other callable type
def load_records(path: str, cls: type) -> list:
with open(path, encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f))
columns = fields(cls)
return [
cls(**{c.name: convert(row[c.name], c.type) for c in columns}) for row in rows
]
def churn_by(records: list, attr: str, enum_cls: type[Enum]) -> None:
for member in enum_cls:
group = [r for r in records if getattr(r, attr) is member]
rate = sum(r.churned for r in group) / len(group)
print(f" {member.value:<15} {len(group):>5,} churn {rate:.1%}")
records = load_records("data/customers.csv", CustomerRecord)
pprint(records[0])
print("by plan:")
churn_by(records, "plan", Plan)
print("by contract:")
churn_by(records, "contract", Contract)
try:
convert("gold", Plan)
except ValueError as exc:
print(exc)
assert len(records) == 5000 and isinstance(records[0].plan, Plan)
assert sum(r.churned for r in records) == 963
Output
CustomerRecord(customer_id='C00001',
plan=<Plan.PREMIUM: 'premium'>,
contract=<Contract.TWO_YEAR: 'two-year'>,
tenure_months=72,
monthly_charges=84.69,
churned=False)
by plan:
basic 2,028 churn 17.4%
standard 1,982 churn 16.0%
premium 990 churn 29.6%
by contract:
month-to-month 2,784 churn 29.6%
one-year 1,225 churn 8.8%
two-year 991 churn 3.2%
'gold' is not a valid Plan; use one of: basic, standard, premium

How it works:

  1. fields(cls) gives the name and the type of each field. The loader needs no code that is specific to customers, so it works for any flat dataclass.
  2. bool is tested first, because bool("0") is True. Enum types get their own branch, which turns the lookup error into a message that lists the valid values. Every other type is called on the text: int("72"), float("84.69"), str("C00001").
  3. Columns of the file that are not fields, such as age, are ignored.
  4. The results match the data dictionary: premium customers churn most (29.6%), and month-to-month contracts churn nine times more than two-year contracts.

Alternative: typing.get_type_hints(cls) resolves annotations written as strings, which you get with from __future__ import annotations. Use it instead of f.type in a library that must handle both.

M21-X02 · Search a grid of churn rules and rank them

Section titled “M21-X02 · Search a grid of churn rules and rank them”
Challenge

A simple churn rule flags a customer when tenure_months <= max_tenure and logins_last_30d <= max_logins. Write a frozen Rule dataclass with those two fields, a __post_init__ that rejects negative values, and a flags(row) method. Build the grid max_tenure in (3, 6, 12) × max_logins in (3, 5, 10) from a base rule with replace(). Score every rule on all customers with precision, recall and F1, store each result in a frozen RuleScore dataclass with order=True that sorts by F1, and print the top 3.

Expected output
tenure <= 12, logins <= 10: f1 0.379 precision 0.366 recall 0.393 flagged 1034
tenure <= 6, logins <= 10: f1 0.356 precision 0.482 recall 0.282 flagged 564
tenure <= 3, logins <= 10: f1 0.288 precision 0.590 recall 0.190 flagged 310
9 rules; 9 distinct
Starter
from dataclasses import dataclass, field, replace
from itertools import product
@dataclass(frozen=True)
class Rule:
max_tenure: int
max_logins: int
# TODO: __post_init__ and flags(row)
@dataclass(frozen=True, order=True)
class RuleScore:
f1: float
# TODO: rule, precision, recall, flagged; none of them compared
customers = [
(int(r["tenure_months"]), int(r["logins_last_30d"]), r["churned"] == "1")
for r in read_csv("data/customers.csv")
]
base = Rule(6, 3)
# TODO: the grid with replace(), the scores, the top 3
Hint 1

For one rule: tp = flagged churners, precision = tp / flagged, recall = tp / all_churners, f1 = 2 * p * r / (p + r). Guard the divisions against 0.

Hint 2

[replace(base, max_tenure=t, max_logins=n) for t, n in product((3, 6, 12), (3, 5, 10))] builds the 9 rules.

Hint 3

Mark the other fields of RuleScore with field(compare=False), then sorted(scores, reverse=True)[:3].

Solution
from dataclasses import dataclass, field, replace
from itertools import product
@dataclass(frozen=True)
class Rule:
max_tenure: int
max_logins: int
def __post_init__(self) -> None:
if self.max_tenure < 0 or self.max_logins < 0:
raise ValueError(f"limits must be >= 0: {self}")
def flags(self, row: tuple[int, int, bool]) -> bool:
tenure, logins, _churned = row
return tenure <= self.max_tenure and logins <= self.max_logins
@dataclass(frozen=True, order=True)
class RuleScore:
f1: float
rule: Rule = field(compare=False)
precision: float = field(compare=False)
recall: float = field(compare=False)
flagged: int = field(compare=False)
def score(rule: Rule, rows: list[tuple[int, int, bool]]) -> RuleScore:
flagged = [row for row in rows if rule.flags(row)]
tp = sum(churned for *_, churned in flagged)
positives = sum(churned for *_, churned in rows)
precision = tp / len(flagged) if flagged else 0.0
recall = tp / positives
f1 = 2 * precision * recall / (precision + recall) if tp else 0.0
return RuleScore(f1, rule, precision, recall, len(flagged))
customers = [
(int(r["tenure_months"]), int(r["logins_last_30d"]), r["churned"] == "1")
for r in read_csv("data/customers.csv")
]
base = Rule(6, 3)
grid = [
replace(base, max_tenure=t, max_logins=n)
for t, n in product((3, 6, 12), (3, 5, 10))
]
scores = [score(rule, customers) for rule in grid]
for s in sorted(scores, reverse=True)[:3]:
r = s.rule
print(
f"tenure <= {r.max_tenure:>2}, logins <= {r.max_logins:>2}: f1 {s.f1:.3f} "
f"precision {s.precision:.3f} recall {s.recall:.3f} flagged {s.flagged:>4}"
)
print(len(grid), "rules;", len(set(grid)), "distinct")
assert max(scores).f1 == sorted(scores)[-1].f1
assert all(isinstance(s.rule, Rule) for s in scores)
Output
tenure <= 12, logins <= 10: f1 0.379 precision 0.366 recall 0.393 flagged 1034
tenure <= 6, logins <= 10: f1 0.356 precision 0.482 recall 0.282 flagged 564
tenure <= 3, logins <= 10: f1 0.288 precision 0.590 recall 0.190 flagged 310
9 rules; 9 distinct

How it works:

  1. replace(base, ...) builds each rule from the base. __post_init__ checks every one.
  2. Rule is frozen, so it is hashable: set(grid) counts the distinct rules, and a rule could be a dict key in a score cache.
  3. RuleScore compares only f1, so sorted(..., reverse=True) ranks by F1 and max() finds the best rule.
  4. The rules trade precision for recall. A wider rule flags more customers and finds more churners, but more of the flagged customers stay. F1 balances the two.

Alternative: scoring the rule on the same data you chose it on overestimates its quality. Choose the rule on training or validation data and score the chosen rule on a test split once, as the project of this module does for KNN.

M21-X03 · Model a training job with a state machine

Section titled “M21-X03 · Model a training job with a state machine”
Challenge

A state machine is a model of a process that is in exactly one state at a time and moves between states only along allowed transitions. A training job is QUEUED, then RUNNING, then SUCCEEDED or FAILED; a queued or running job can be CANCELLED. Write the JobState enum, a dict of allowed transitions, and a dataclass TrainingJob with name, state (starts QUEUED) and a history list (default_factory). Its method move_to(new_state) raises ValueError for a forbidden transition. A property is_final uses match. Replay the event log of the starter and print what happens.

Expected output
logreg: cannot go from RUNNING to QUEUED
knn-k15: cannot go from SUCCEEDED to RUNNING
hgb: unknown state 'PAUSED'
knn-k15 final=True QUEUED -> RUNNING -> SUCCEEDED
logreg final=True QUEUED -> RUNNING -> FAILED
hgb final=True QUEUED -> CANCELLED
Starter
from dataclasses import dataclass, field
from enum import Enum, auto
class JobState(Enum):
QUEUED = auto()
# TODO: RUNNING, SUCCEEDED, FAILED, CANCELLED
ALLOWED: dict[JobState, frozenset[JobState]] = {
# TODO: one entry per state
}
@dataclass
class TrainingJob:
name: str
# TODO: state, history, move_to(), is_final
events = [
("knn-k15", "RUNNING"),
("knn-k15", "SUCCEEDED"),
("logreg", "RUNNING"),
("logreg", "QUEUED"),
("logreg", "FAILED"),
("knn-k15", "RUNNING"),
("hgb", "CANCELLED"),
("hgb", "PAUSED"),
]
# TODO: create jobs on first use, replay the events, print errors and a final summary
Hint 1

Final states have no way out: ALLOWED[JobState.SUCCEEDED] = frozenset().

Hint 2

Parse the event text by name: JobState[text]. An unknown name raises KeyError.

Hint 3

is_final can be match self.state: with case JobState.SUCCEEDED | JobState.FAILED | JobState.CANCELLED: return True and case _: return False.

Solution
from dataclasses import dataclass, field
from enum import Enum, auto
class JobState(Enum):
QUEUED = auto()
RUNNING = auto()
SUCCEEDED = auto()
FAILED = auto()
CANCELLED = auto()
ALLOWED: dict[JobState, frozenset[JobState]] = {
JobState.QUEUED: frozenset({JobState.RUNNING, JobState.CANCELLED}),
JobState.RUNNING: frozenset(
{JobState.SUCCEEDED, JobState.FAILED, JobState.CANCELLED}
),
JobState.SUCCEEDED: frozenset(),
JobState.FAILED: frozenset(),
JobState.CANCELLED: frozenset(),
}
@dataclass
class TrainingJob:
name: str
state: JobState = JobState.QUEUED
history: list[JobState] = field(default_factory=list)
def move_to(self, new_state: JobState) -> None:
if new_state not in ALLOWED[self.state]:
old, new = self.state.name, new_state.name
raise ValueError(f"{self.name}: cannot go from {old} to {new}")
self.history.append(self.state)
self.state = new_state
@property
def is_final(self) -> bool:
match self.state:
case JobState.SUCCEEDED | JobState.FAILED | JobState.CANCELLED:
return True
case _:
return False
events = [
("knn-k15", "RUNNING"),
("knn-k15", "SUCCEEDED"),
("logreg", "RUNNING"),
("logreg", "QUEUED"),
("logreg", "FAILED"),
("knn-k15", "RUNNING"),
("hgb", "CANCELLED"),
("hgb", "PAUSED"),
]
jobs: dict[str, TrainingJob] = {}
for name, text in events:
job = jobs.setdefault(name, TrainingJob(name))
try:
job.move_to(JobState[text])
except KeyError:
print(f"{name}: unknown state {text!r}")
except ValueError as exc:
print(exc)
for job in jobs.values():
path = " -> ".join(s.name for s in [*job.history, job.state])
print(f"{job.name:<8} final={job.is_final!s:<5} {path}")
assert jobs["knn-k15"].state is JobState.SUCCEEDED
assert all(job.is_final for job in jobs.values())
Output
logreg: cannot go from RUNNING to QUEUED
knn-k15: cannot go from SUCCEEDED to RUNNING
hgb: unknown state 'PAUSED'
knn-k15 final=True QUEUED -> RUNNING -> SUCCEEDED
logreg final=True QUEUED -> RUNNING -> FAILED
hgb final=True QUEUED -> CANCELLED

How it works:

  1. The enum names the five states. The dict of frozensets is the transition table: one place to read and change the rules.
  2. history uses default_factory=list, so each job has its own history. A plain state default is fine, because an enum member is immutable.
  3. move_to validates before it changes anything, so a rejected event leaves the job as it was.
  4. The or-pattern JobState.SUCCEEDED | JobState.FAILED | JobState.CANCELLED combines three value patterns in one case.
  5. jobs.setdefault(name, TrainingJob(name)) creates a job the first time its name appears.

Alternative: store the allowed next states on the enum itself with a property and a match. The table in a dict is easier to print and to test.

M21-X04 · Find the latest production model in a registry

Section titled “M21-X04 · Find the latest production model in a registry”
Challenge

A model registry stores entries as JSON. Write a frozen ModelVersion(major, minor, patch) dataclass with order=True, a class method parse("1.10.0") and a __str__. Write a Stage(StrEnum) with STAGING, PRODUCTION, ARCHIVED, and a frozen Entry(name, version, stage, metrics) with metrics defaulting to an empty dict and left out of == and the hash. Load the JSON of the starter, print the latest production version of each model, then “promote” churn-knn 1.10.0 to production with replace() and archive the old production version.

Expected output
churn-knn 1.2.3 {'recall': 0.18}
price-lr 2.0.1 {'r2': 0.56}
after promotion:
churn-knn 0.9.12 archived
churn-knn 1.2.3 archived
churn-knn 1.10.0 production
price-lr 2.0.0 production
price-lr 2.0.1 production
Starter
import json
from dataclasses import dataclass, field, replace
from enum import StrEnum, auto
from typing import Self
REGISTRY = """[
{"name": "churn-knn", "version": "1.2.3", "stage": "production",
"metrics": {"recall": 0.18}},
{"name": "churn-knn", "version": "1.10.0", "stage": "staging",
"metrics": {"recall": 0.24}},
{"name": "churn-knn", "version": "0.9.12", "stage": "archived"},
{"name": "price-lr", "version": "2.0.0", "stage": "production",
"metrics": {"r2": 0.55}},
{"name": "price-lr", "version": "2.0.1", "stage": "production",
"metrics": {"r2": 0.56}}
]"""
# TODO: ModelVersion, Stage, Entry
# TODO: parse the JSON into entries
# TODO: print the latest production version per model name
# TODO: promote churn-knn 1.10.0, archive the old production entry, print the result
Hint 1

parse splits the text: cls(*(int(part) for part in text.split("."))).

Hint 2

Latest per model: filter the production entries, then max(group, key=lambda e: e.version). Versions compare as tuples of ints, so 1.10.0 > 1.2.3.

Hint 3

A frozen dataclass hashes all compared fields, and a dict is unhashable. field(default_factory=dict, compare=False) keeps metrics out of == and the hash. Frozen entries cannot change. Build a new list in which the two affected entries are replaced by replace(entry, stage=Stage.PRODUCTION) and replace(entry, stage=Stage.ARCHIVED).

Solution
import json
from dataclasses import dataclass, field, replace
from enum import StrEnum, auto
from typing import Self
REGISTRY = """[
{"name": "churn-knn", "version": "1.2.3", "stage": "production",
"metrics": {"recall": 0.18}},
{"name": "churn-knn", "version": "1.10.0", "stage": "staging",
"metrics": {"recall": 0.24}},
{"name": "churn-knn", "version": "0.9.12", "stage": "archived"},
{"name": "price-lr", "version": "2.0.0", "stage": "production",
"metrics": {"r2": 0.55}},
{"name": "price-lr", "version": "2.0.1", "stage": "production",
"metrics": {"r2": 0.56}}
]"""
@dataclass(frozen=True, order=True)
class ModelVersion:
major: int
minor: int
patch: int
@classmethod
def parse(cls, text: str) -> Self:
return cls(*(int(part) for part in text.split(".")))
def __str__(self) -> str:
return f"{self.major}.{self.minor}.{self.patch}"
class Stage(StrEnum):
STAGING = auto()
PRODUCTION = auto()
ARCHIVED = auto()
@dataclass(frozen=True)
class Entry:
name: str
version: ModelVersion
stage: Stage
metrics: dict[str, float] = field(default_factory=dict, compare=False)
def latest_production(entries: list[Entry]) -> dict[str, Entry]:
best: dict[str, Entry] = {}
for e in entries:
if e.stage is not Stage.PRODUCTION:
continue
if e.name not in best or e.version > best[e.name].version:
best[e.name] = e
return best
def entry_from_json(d: dict) -> Entry:
version = ModelVersion.parse(d["version"])
return Entry(d["name"], version, Stage(d["stage"]), d.get("metrics", {}))
entries = [entry_from_json(d) for d in json.loads(REGISTRY)]
for name, e in latest_production(entries).items():
print(f"{name:<10} {e.version!s:<7} {e.metrics}")
old = latest_production(entries)["churn-knn"]
new = next(e for e in entries if e.name == "churn-knn" and str(e.version) == "1.10.0")
changes = {
old: replace(old, stage=Stage.ARCHIVED),
new: replace(new, stage=Stage.PRODUCTION),
}
entries = [changes.get(e, e) for e in entries]
print("after promotion:")
for e in sorted(entries, key=lambda e: (e.name, e.version)):
print(f" {e.name:<10} {e.version!s:<7} {e.stage}")
assert latest_production(entries)["churn-knn"].version == ModelVersion(1, 10, 0)
Output
churn-knn 1.2.3 {'recall': 0.18}
price-lr 2.0.1 {'r2': 0.56}
after promotion:
churn-knn 0.9.12 archived
churn-knn 1.2.3 archived
churn-knn 1.10.0 production
price-lr 2.0.0 production
price-lr 2.0.1 production

How it works:

  1. order=True compares versions as (major, minor, patch) tuples of ints, so 1.10.0 is newer than 1.2.3. String comparison would get this wrong.
  2. Stage(d["stage"]) validates the stage text. StrEnum members print as their value in the table.
  3. changes = {old: ..., new: ...} uses entries as dict keys, so Entry must be hashable. The generated hash of a frozen dataclass hashes every compared field, and hash() of a dict raises TypeError: unhashable type: 'dict'. compare=False keeps metrics out of == and out of the hash. Two entries are then equal when name, version and stage match, which is the identity of a registry entry anyway.
  4. replace() gives the changed entries. changes.get(e, e) swaps them in and keeps the others unchanged.

Alternative: use (e.name, e.version) as the key of changes instead of the entry itself. A key made of hashable parts avoids the problem without changing the class.

M21-X05 · Summarize sensors within a memory budget

Section titled “M21-X05 · Summarize sensors within a memory budget”
Challenge

A monitoring job may use at most 80 bytes per reading for its records. Load every row of data/sensors.csv into a frozen, slotted dataclass Reading(sensor_id, temperature_c, severity), where temperature_c is float | None and severity is the Severity IntEnum of exercise C07. Measure the bytes per record with tracemalloc (parse the values first, then measure only the record objects) and check the budget. Then build one SensorSummary(mean_c, sensor_id, n_alerts, worst) per sensor, with order=True on mean_c only, and print the sensors from warmest to coolest.

Expected output
8,064 readings, 56 bytes per record
within the 80-byte budget: True
S4: mean 26.04 °C alerts 419 worst FAIL
S2: mean 24.60 °C alerts 22 worst FAIL
S3: mean 23.53 °C alerts 22 worst WARN
S1: mean 22.05 °C alerts 14 worst WARN
Starter
import statistics
import tracemalloc
from dataclasses import dataclass, field
from enum import IntEnum
class Severity(IntEnum):
OK = 0
WARN = 1
FAIL = 2
@dataclass(frozen=True, slots=True)
class Reading:
sensor_id: str
temperature_c: float | None
severity: Severity
@dataclass(frozen=True, order=True)
class SensorSummary:
mean_c: float
# TODO: sensor_id, n_alerts, worst: not compared
# TODO: parse the values (outside the measurement)
# TODO: measure the records, check the budget
# TODO: one summary per sensor, warmest first
Hint 1

Parse with (row["sensor_id"], float(t) if t else None, Severity[row["status"].upper()]), then measure [Reading(*v) for v in values] between tracemalloc.start() and get_traced_memory(). Subtract the cost of the list with a baseline [None for v in values].

Hint 2

Skip None temperatures in the mean. worst = max(r.severity for r in group).

Solution
import statistics
import tracemalloc
from dataclasses import dataclass, field
from enum import IntEnum
class Severity(IntEnum):
OK = 0
WARN = 1
FAIL = 2
@dataclass(frozen=True, slots=True)
class Reading:
sensor_id: str
temperature_c: float | None
severity: Severity
@dataclass(frozen=True, order=True)
class SensorSummary:
mean_c: float
sensor_id: str = field(compare=False)
n_alerts: int = field(compare=False)
worst: Severity = field(compare=False)
values = [
(
row["sensor_id"],
float(row["temperature_c"]) if row["temperature_c"] else None,
Severity[row["status"].upper()],
)
for row in read_csv("data/sensors.csv")
]
def traced_bytes(build) -> tuple[list, int]:
tracemalloc.start()
result = build()
used, _peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return result, used
_, list_only = traced_bytes(lambda: [None for _v in values])
readings, used = traced_bytes(lambda: [Reading(*v) for v in values])
per_record = (used - list_only) / len(readings)
print(f"{len(readings):,} readings, {per_record:.0f} bytes per record")
print("within the 80-byte budget:", per_record <= 80)
summaries = []
for sensor in sorted({r.sensor_id for r in readings}):
group = [r for r in readings if r.sensor_id == sensor]
temps = [r.temperature_c for r in group if r.temperature_c is not None]
alerts = sum(r.severity > Severity.OK for r in group)
worst = max(r.severity for r in group)
mean_c = round(statistics.fmean(temps), 2)
summaries.append(SensorSummary(mean_c, sensor, alerts, worst))
for s in sorted(summaries, reverse=True):
alerts = f"alerts {s.n_alerts:>3}"
print(f"{s.sensor_id}: mean {s.mean_c:.2f} °C {alerts} worst {s.worst.name}")
assert per_record <= 80
ranking = [s.sensor_id for s in sorted(summaries, reverse=True)]
assert ranking == ["S4", "S2", "S3", "S1"]
Output
8,064 readings, 56 bytes per record
within the 80-byte budget: True
S4: mean 26.04 °C alerts 419 worst FAIL
S2: mean 24.60 °C alerts 22 worst FAIL
S3: mean 23.53 °C alerts 22 worst WARN
S1: mean 22.05 °C alerts 14 worst WARN

How it works:

  1. The values are parsed before the measurement, so tracemalloc counts only the Reading objects. The baseline removes the list of references.
  2. A slotted dataclass with three fields stays well inside the budget. A dict per reading would not (184 bytes for four keys in the lesson).
  3. Severities are IntEnum members, shared by all readings, so they cost nothing per record. max() and > work because the members are ordered.
  4. SensorSummary compares only mean_c, so sorted(..., reverse=True) lists the warmest sensor first.

Alternative: keep three parallel lists (or one NumPy array per column, module 23) instead of one object per reading. Column storage is much smaller again, at the cost of per-row objects with names.