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:
- Read the task and the expected output.
- Copy the setup block and the starter code into a script (for example
exercise.py). Replace each to-do comment with your code. - Run the script with
python exercise.py. Compare your output with the expected output. - 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
Section titled “Warm-up”M21-W01 · Write a fit report dataclass
Section titled “M21-W01 · Write a fit report dataclass”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.
FitReport(model='KNNClassifier(n_neighbors=15)', n_train=938, test_score=0.824)True FalseKNNClassifier(n_neighbors=15): 82.4%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 lineHint 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
@dataclassclass 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 againassert knn != FitReport("KNNClassifier(n_neighbors=1)", 938, 0.696)FitReport(model='KNNClassifier(n_neighbors=15)', n_train=938, test_score=0.824)True FalseKNNClassifier(n_neighbors=15): 82.4%How it works:
@dataclassreads the three annotations and generates__init__(self, model, n_train, test_score).- The generated
__repr__shows the class name and every field withrepr(), so the model name keeps its quotes. - The generated
__eq__compares the fields as a tuple. The two reports are equal but they are two objects, soisgivesFalse.
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).
M21-W02 · Fix the bug: a list default
Section titled “M21-W02 · Fix the bug: a list default”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.
Experiment(name='knn-k5', tags=['baseline'])Experiment(name='knn-k15', tags=[])from dataclasses import dataclass
@dataclassclass 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
@dataclassclass 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.tagsExperiment(name='knn-k5', tags=['baseline'])Experiment(name='knn-k15', tags=[])How it works:
- The class body runs once. A list written there would be one object shared by every instance, the mutable default gotcha of module 13.
@dataclassrefuses such a default with theValueErrorfrom the task.default_factory=liststores the functionlist, 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”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.
from dataclasses import dataclass, field
@dataclassclass 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
@dataclassclass 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 != cReading(sensor_id='S1', temperature_c=20.21, note='')True FalseReading(sensor_id='S1', temperature_c=20.21, note='checked by hand')True2How it works:
- Line 1: the repr shows every field, also
notewith its default''.compare=Falsedoes not hide a field;repr=Falsewould. - Line 2:
a == bcompares onlysensor_idandtemperature_c, so the different notes do not matter.a == cisFalsebecause the sensor ids differ. - Line 3:
bshows its note. - Line 4: the class defines
__eq__and is not frozen, so@dataclasssets__hash__toNone. Instances are unhashable. - Line 5: two of the three readings come from sensor S1.
M21-W04 · Freeze a decision threshold
Section titled “M21-W04 · Freeze a decision threshold”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.
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.5import jsonfrom 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 messageHint 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 jsonfrom 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.3except 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.3assert hash(threshold) == hash(DecisionThreshold(0.5))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.5How it works:
frozen=Trueblocks every assignment after__init__withFrozenInstanceError.replace()builds a new object through__init__, so the copy is validated too, and the original stays at 0.5.- 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”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.
ok 7,587warn 453fail 24True Truefrom collections import Counterfrom 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.WARNHint 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 Counterfrom 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()) == 8064assert counts[Status.FAIL] == 24ok 7,587warn 453fail 24True TrueHow it works:
Status(row["status"])looks a member up by its value. An unexpected code such as"error"would raiseValueErrorat once.- The members are hashable, so they work as
Counterkeys. f"{status:<5}"formats aStrEnummember like its string value.- 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”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.
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[<Channel.ONLINE: 'online'>, <Channel.STORE: 'store'>]True FalseRegion.SOUTH 1store|Region.SOUTHTrue 2How it works:
- Line 1: a list shows the repr of each member, with the values that
auto()chose. - Line 2: the
StrEnummember equals its string. The plainEnummember does not equal its integer value. - Line 3:
Region(2)looks up by value and prints asRegion.SOUTH.Region["NORTH"]looks up by name; its value is 1. - Line 4: in an f-string, the
StrEnummember shows its value, the plain member showsClass.NAME. - Line 5: since Python 3.12,
inaccepts a value. The enum has two members.
M21-W07 · Read stores into a NamedTuple
Section titled “M21-W07 · Read stores into a NamedTuple”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().
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)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=3000Hint 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 = largestprint(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 copyStore(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:
- A named tuple has a field name for each position.
largest.size_sqmandlargest[3]are the same value. key=lambda s: s.size_sqmis needed: without it,max()would compare the tuples from the first field, the store id.- A named tuple unpacks like any tuple.
- Named tuples are immutable.
_replace()returns a new tuple and leavesstores[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”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.
('x', 'y', 'label') False'LabelledPoint' object has no attribute 'lable' and no __dict__ for setting new attributeslabel is still 1class 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 labelHint 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, churnedprint(LabelledPoint.__slots__, hasattr(point, "__dict__"))try: point.lable = 0except AttributeError as exc: print(exc)print("label is still", point.label)assert not hasattr(point, "__dict__")('x', 'y', 'label') False'LabelledPoint' object has no attribute 'lable' and no __dict__ for setting new attributeslabel is still 1How it works:
__slots__lists the only attribute names an instance can have. Python reserves one slot per name and creates no__dict__.- The typo
lableis not a slot, so the assignment fails instead of adding a new attribute. - The real
labelkeeps 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”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.
5000 Customer(customer_id='C00001', age=18, tenure_months=72, churned=False)churned: 963rejected: bad customer_id 'C1'rejected: C00042: age 17 outside 18-80rejected: C00043: negative tenure -2from dataclasses import dataclassfrom typing import Self
@dataclassclass 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 errorHint 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 dataclassfrom typing import Self
@dataclassclass 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) == 5000assert sum(c.churned for c in customers) == 9635000 Customer(customer_id='C00001', age=18, tenure_months=72, churned=False)churned: 963rejected: bad customer_id 'C1'rejected: C00042: age 17 outside 18-80rejected: C00043: negative tenure -2How it works:
from_rowconverts text to the field types. The class method is the alternative constructor of module 18.- The generated
__init__stores the values and then calls__post_init__, so every way of creating aCustomerruns the checks. Truecounts as 1 insum(), sosum(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”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.
OrderLine(order_id='O000001', unit_price=69.99, quantity=1, discount=0.05, revenue=66.49)lines that differ: 9, largest difference: 0.01 USDtotal revenue: 178,725.93 USDfrom 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 totalHint 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 centassert lines[0].revenue == 66.49OrderLine(order_id='O000001', unit_price=69.99, quantity=1, discount=0.05, revenue=66.49)lines that differ: 9, largest difference: 0.01 USDtotal revenue: 178,725.93 USDHow it works:
field(init=False)keepsrevenueout of__init__, so a caller cannot pass a wrong value.object.__setattr__sets the field once, while the frozen object is being built.- The revenue is a field, so it appears in the repr and takes part in
==and the hash. - 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”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.
1. HistGradientBoosting (tuned) 0.8472. HistGradientBoosting 0.8313. LogisticRegression 0.8144. DummyClassifier 0.500best: HistGradientBoosting (tuned)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 nameHint 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.847assert CVResult(0.5, "a") == CVResult(0.5, "b") # the model name is not compared1. HistGradientBoosting (tuned) 0.8472. HistGradientBoosting 0.8313. LogisticRegression 0.8144. DummyClassifier 0.500best: HistGradientBoosting (tuned)How it works:
order=Truegenerates<,<=,>,>=from the tuple of compared fields, here only(mean_auc,).sorted(..., reverse=True)andmax()use those methods.compare=Falsealso removesmodelfrom==: 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”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).
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)Trueclass 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 statisticsfrom collections import defaultdictfrom dataclasses import dataclass
@dataclassclass 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 - 22SensorSummary(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)TrueHow it works:
- The dataclass generates the same three methods from three lines. The repr text is identical to the hand-written one.
- 22 temperature cells are blank, so the counts add up to 8,042.
- 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”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.
{"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 Falseimport jsonfrom dataclasses import asdict, dataclass, fieldfrom typing import Any, Self
@dataclass(frozen=True)class TrainConfig: learning_rate: float = 0.01 epochs: int = 100
@dataclassclass 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 expHint 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 jsonfrom dataclasses import asdict, dataclass, fieldfrom typing import Any, Self
@dataclass(frozen=True)class TrainConfig: learning_rate: float = 0.01 epochs: int = 100
@dataclassclass 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 == expassert exp.scores == [0.81, 0.83]{"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 FalseHow it works:
asdict()works recursively: the nestedTrainConfigbecomes a nested dict, and the list is copied.- Appending to
d["scores"]does not touchexp.scores:asdict()shares no mutable data with the object. from_dictrebuilds 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”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.
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_CHECKfrom collections import Counterfrom 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 rateHint 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 Counterfrom 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()) == 5000assert worst is PaymentMethod.ELECTRONIC_CHECKelectronic_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_CHECKHow it works:
- The member names are the file values in upper case, so
auto()produces exactly the values in the file. PaymentMethod(...)rejects any other text, so a new method in next month’s export would stop the script instead of vanishing from the report.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”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.
S1: worst WARN alerts 14S2: worst FAIL alerts 22S3: worst WARN alerts 22S4: worst FAIL alerts 419from collections import defaultdictfrom 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 OKHint 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 defaultdictfrom 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.FAILassert sum(v == Severity.FAIL for v in levels["S2"]) == 5S1: worst WARN alerts 14S2: worst FAIL alerts 22S3: worst WARN alerts 22S4: worst FAIL alerts 419How it works:
Severity[...]looks up by name..upper()turns the file value into the name.IntEnummembers compare as ints, somax()returns the worst level. A plainEnumwould raiseTypeErroron<.max()returns a member, so.namegivesFAILand not2.- 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”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.
mean S1=22.05 S2=24.60 S3=23.53 S4=26.04max S1=38.63 S2=44.89 S3=41.66 S4=44.36import statisticsfrom collections import defaultdictfrom 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 valuesHint 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 statisticsfrom collections import defaultdictfrom 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.04mean S1=22.05 S2=24.60 S3=23.53 S4=26.04max S1=38.63 S2=44.89 S3=41.66 S4=44.36How it works:
Aggregation(setting)turns the user’s text into a member, or raisesValueErrorfor anything else.- The
matchlists one formula per member with dotted value patterns.case _catches a member that someone adds later without a formula. - 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”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.
EUCLIDEAN square root of the sum of squared differencesMANHATTAN sum of absolute differencesCHEBYSHEV largest absolute differencefrom 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")EUCLIDEAN square root of the sum of squared differencesMANHATTAN sum of absolute differencesCHEBYSHEV largest absolute differenceHow it works:
- In the starter,
case MANHATTAN:is a capture pattern: it binds any subject to a new local nameMANHATTAN. As the last case, it is allowed, and it matchedCHEBYSHEV. - Dotted names such as
Distance.MANHATTANare value patterns. They compare with==. - 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”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.
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: 423500import statisticsfrom typing import NamedTuple
class Comp(NamedTuple): house_id: str sqft_gap: int price: int
target_sqft = 1835comps = [ 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 fieldfor 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 statisticsfrom typing import NamedTuple
class Comp(NamedTuple): house_id: str sqft_gap: int price: int
target_sqft = 1835comps = [ 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) == 370Comp(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: 423500How it works:
- A named tuple sorts as a tuple: by its first field, then the second. For
Comp, that ishouse_id, so the starter returned the three smallest ids. - 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. - 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.
M21-C11 · Choose the right record type
Section titled “M21-C11 · Choose the right record type”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.
- The parsed
data/config.jsonthat a training script passes to ten functions. No code may change it. - The JSON body of a
POST /predictrequest from a public web form. - 10 million sensor readings kept in memory by a monitoring job. The values are updated in place when a correction arrives.
- A
KNNClassifierwithfit(),predict()and learned attributes. - Type hints for the records of
data/customers.json, which the code loads and passes on unchanged. - A function that returns
(mean, std). Old code unpacks the result as a pair.
1. frozen dataclass2. pydantic model3. slotted dataclass4. plain class5. TypedDict6. NamedTuplechoices = { 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())) == 61. frozen dataclass2. pydantic model3. slotted dataclass4. plain class5. TypedDict6. NamedTupleHow it works:
- Config: a frozen dataclass validates in
__post_init__, names every setting and blocks changes. Ten functions can share it safely. - Web request: the input is untrusted. A pydantic model checks and converts every field and returns clear errors (module 44).
- 10 million readings:
slots=Truecuts the memory per object, and the instances stay mutable for corrections. ANamedTupleis small too, but it is immutable. - Estimator: it has behavior and state that changes during
fit(). A plain class (onBaseEstimator) fits. Its parameters are stored unchanged, as scikit-learn expects. - JSON records passed on: a
TypedDictadds type hints with no conversion and no copy. The values stay plain dicts, which is what the next function expects. - (mean, std): a
NamedTuplekeepsmean, std = resultworking and addsresult.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”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.
str 57.0 bytes per rowPlan 8.6 bytes per row['premium', 'standard'] [<Plan.PREMIUM: 'premium'>, <Plan.STANDARD: 'standard'>]True 3import csvimport tracemallocfrom collections.abc import Callablefrom 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 rowHint 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 csvimport tracemallocfrom collections.abc import Callablefrom 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 / 4str 57.0 bytes per rowPlan 8.6 bytes per row['premium', 'standard'] [<Plan.PREMIUM: 'premium'>, <Plan.STANDARD: 'standard'>]True 3How it works:
- The string list keeps 5,000 separate string objects, one per row, plus the list: about 57 bytes per row.
- 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.
str(row["plan"])returns the same string object, so the string list really holds the strings that the reader created.StrEnummembers 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”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.
KNNSpec(name='knn', random_state=42, n_neighbors=15)TypeError: KNNSpec.__init__() takes from 2 to 3 positional arguments but 4 were givenfrom dataclasses import dataclass
@dataclassclass ModelSpec: name: str random_state: int = 42
@dataclass # TODO: fix this classclass 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 messageHint 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
@dataclassclass 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 == 15KNNSpec(name='knn', random_state=42, n_neighbors=15)TypeError: KNNSpec.__init__() takes from 2 to 3 positional arguments but 4 were givenHow it works:
kw_only=Trueapplies to the fields defined inKNNSpec, not to the inherited ones. Sonameandrandom_statestay positional.- A keyword-only parameter may come after parameters with defaults, so the class can be created.
- The call with three positional arguments fails:
n_neighborsmust be named. This makes calls readable.
Alternative: n_neighbors: int = field(kw_only=True) marks only this field. Or write _: KW_ONLY before it.
Challenge
Section titled “Challenge”M21-X01 · Write a typed CSV loader for any dataclass
Section titled “M21-X01 · Write a typed CSV loader for any dataclass”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".
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, premiumimport csvfrom dataclasses import dataclass, fieldsfrom enum import Enum, StrEnum, autofrom 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 csvfrom dataclasses import dataclass, fieldsfrom enum import Enum, StrEnum, autofrom pprint import pprintfrom 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) == 963CustomerRecord(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, premiumHow it works:
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.boolis tested first, becausebool("0")isTrue. 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").- Columns of the file that are not fields, such as
age, are ignored. - 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”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.
tenure <= 12, logins <= 10: f1 0.379 precision 0.366 recall 0.393 flagged 1034tenure <= 6, logins <= 10: f1 0.356 precision 0.482 recall 0.282 flagged 564tenure <= 3, logins <= 10: f1 0.288 precision 0.590 recall 0.190 flagged 3109 rules; 9 distinctfrom dataclasses import dataclass, field, replacefrom 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 3Hint 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, replacefrom 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].f1assert all(isinstance(s.rule, Rule) for s in scores)tenure <= 12, logins <= 10: f1 0.379 precision 0.366 recall 0.393 flagged 1034tenure <= 6, logins <= 10: f1 0.356 precision 0.482 recall 0.282 flagged 564tenure <= 3, logins <= 10: f1 0.288 precision 0.590 recall 0.190 flagged 3109 rules; 9 distinctHow it works:
replace(base, ...)builds each rule from the base.__post_init__checks every one.Ruleis frozen, so it is hashable:set(grid)counts the distinct rules, and a rule could be a dict key in a score cache.RuleScorecompares onlyf1, sosorted(..., reverse=True)ranks by F1 andmax()finds the best rule.- 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”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.
logreg: cannot go from RUNNING to QUEUEDknn-k15: cannot go from SUCCEEDED to RUNNINGhgb: unknown state 'PAUSED'knn-k15 final=True QUEUED -> RUNNING -> SUCCEEDEDlogreg final=True QUEUED -> RUNNING -> FAILEDhgb final=True QUEUED -> CANCELLEDfrom dataclasses import dataclass, fieldfrom enum import Enum, auto
class JobState(Enum): QUEUED = auto() # TODO: RUNNING, SUCCEEDED, FAILED, CANCELLED
ALLOWED: dict[JobState, frozenset[JobState]] = { # TODO: one entry per state}
@dataclassclass 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 summaryHint 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, fieldfrom 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(),}
@dataclassclass 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.SUCCEEDEDassert all(job.is_final for job in jobs.values())logreg: cannot go from RUNNING to QUEUEDknn-k15: cannot go from SUCCEEDED to RUNNINGhgb: unknown state 'PAUSED'knn-k15 final=True QUEUED -> RUNNING -> SUCCEEDEDlogreg final=True QUEUED -> RUNNING -> FAILEDhgb final=True QUEUED -> CANCELLEDHow it works:
- The enum names the five states. The dict of frozensets is the transition table: one place to read and change the rules.
historyusesdefault_factory=list, so each job has its own history. A plainstatedefault is fine, because an enum member is immutable.move_tovalidates before it changes anything, so a rejected event leaves the job as it was.- The or-pattern
JobState.SUCCEEDED | JobState.FAILED | JobState.CANCELLEDcombines three value patterns in one case. 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”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.
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 productionimport jsonfrom dataclasses import dataclass, field, replacefrom enum import StrEnum, autofrom 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 resultHint 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 jsonfrom dataclasses import dataclass, field, replacefrom enum import StrEnum, autofrom 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)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 productionHow it works:
order=Truecompares versions as(major, minor, patch)tuples of ints, so 1.10.0 is newer than 1.2.3. String comparison would get this wrong.Stage(d["stage"])validates the stage text.StrEnummembers print as their value in the table.changes = {old: ..., new: ...}uses entries as dict keys, soEntrymust be hashable. The generated hash of a frozen dataclass hashes every compared field, andhash()of a dict raisesTypeError: unhashable type: 'dict'.compare=Falsekeepsmetricsout 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.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”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.
8,064 readings, 56 bytes per recordwithin the 80-byte budget: TrueS4: mean 26.04 °C alerts 419 worst FAILS2: mean 24.60 °C alerts 22 worst FAILS3: mean 23.53 °C alerts 22 worst WARNS1: mean 22.05 °C alerts 14 worst WARNimport statisticsimport tracemallocfrom dataclasses import dataclass, fieldfrom 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 firstHint 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 statisticsimport tracemallocfrom dataclasses import dataclass, fieldfrom 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 <= 80ranking = [s.sensor_id for s in sorted(summaries, reverse=True)]assert ranking == ["S4", "S2", "S3", "S1"]8,064 readings, 56 bytes per recordwithin the 80-byte budget: TrueS4: mean 26.04 °C alerts 419 worst FAILS2: mean 24.60 °C alerts 22 worst FAILS3: mean 23.53 °C alerts 22 worst WARNS1: mean 22.05 °C alerts 14 worst WARNHow it works:
- The values are parsed before the measurement, so
tracemalloccounts only theReadingobjects. The baseline removes the list of references. - 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).
- Severities are
IntEnummembers, shared by all readings, so they cost nothing per record.max()and>work because the members are ordered. SensorSummarycompares onlymean_c, sosorted(..., 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.