18. Classes and objects — Exercises
These exercises practice every idea of the Classes and objects lesson. They model the course datasets as objects: products, stores, houses, customers, sensor readings, sales lines and reviews. Some exercises leave data science: a game entity, an HTTP request and a model registry.
How to work:
- Read the task and the expected output.
- Copy the starter code into a script (for example
exercise.py) in your project folder and 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. Each solution is self-contained: it has all its imports and classes, so you can run it alone.
Warm-up
Section titled “Warm-up”M18-W01 · A product with a margin
Section titled “M18-W01 · A product with a margin”Write a class Product for rows of data/products.csv. __init__ takes product_id, name, unit_cost and unit_price. Add a method margin() that returns unit_price - unit_cost rounded to 2 decimals, and a method margin_rate() that returns the margin divided by the price, rounded to 3 decimals. Create P001 (Wireless Earbuds, cost 31.5, price 79.99) and P002 (Noise-Cancelling Headphones, cost 104.0, price 249.0) and print one line for each.
P001 Wireless Earbuds: margin 48.49 USD (60.6%)P002 Noise-Cancelling Headphones: margin 145.0 USD (58.2%)class Product: def __init__(self, product_id: str, name: str, unit_cost: float, unit_price: float): # TODO: store the four values as instance attributes ...
# TODO: margin() and margin_rate()
earbuds = Product("P001", "Wireless Earbuds", 31.5, 79.99)headphones = Product("P002", "Noise-Cancelling Headphones", 104.0, 249.0)# TODO: print "P001 Wireless Earbuds: margin 48.49 USD (60.6%)" and the same for P002Hint 1
Each line of __init__ has the form self.name = name. Inside a method, read the values back with self.unit_price.
Hint 2
margin_rate() can call the other method: self.margin() / self.unit_price. In the f-string, :.1% shows a fraction as a percentage with one decimal.
Solution
class Product: def __init__(self, product_id: str, name: str, unit_cost: float, unit_price: float): self.product_id = product_id self.name = name self.unit_cost = unit_cost self.unit_price = unit_price
def margin(self) -> float: return round(self.unit_price - self.unit_cost, 2)
def margin_rate(self) -> float: return round(self.margin() / self.unit_price, 3)
earbuds = Product("P001", "Wireless Earbuds", 31.5, 79.99)headphones = Product("P002", "Noise-Cancelling Headphones", 104.0, 249.0)for p in (earbuds, headphones): print(f"{p.product_id} {p.name}: margin {p.margin()} USD ({p.margin_rate():.1%})")
assert earbuds.margin() == 48.49assert headphones.margin_rate() == 0.582assert vars(earbuds)["unit_cost"] == 31.5P001 Wireless Earbuds: margin 48.49 USD (60.6%)P002 Noise-Cancelling Headphones: margin 145.0 USD (58.2%)How it works:
__init__stores the four arguments onself, so eachProductinstance has its own four attributes.margin()reads two attributes of the instance it is called on. Forearbuds,selfisearbuds.margin_rate()callsself.margin(), so the margin formula exists in one place only.- The loop treats both objects the same way, because they share the methods of the class.
Alternative: margin could be a property (@property def margin(self)), so callers write p.margin without parentheses. Use a property for a cheap value that reads like data; use a method when the call does real work or takes arguments.
M18-W02 · Predict the output: class and instance attributes
Section titled “M18-W02 · Predict the output: class and instance attributes”Predict the output: write down what each print shows. Then run the code and compare.
Acceptance criteria:
- Write your prediction for all four lines 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 say in which namespace Python found the value.
class Store: currency = "USD"
def __init__(self, store_id: str): self.store_id = store_id
s1 = Store("S01")s2 = Store("S02")s1.currency = "EUR"Store.currency = "CAD"print(s1.currency, s2.currency, Store.currency)print(vars(s1))print(vars(s2))del s1.currencyprint(s1.currency)# TODO: write your prediction for each print before you run itHint 1
s1.currency = "EUR" is an assignment through an instance. Where does it store the value?
Hint 2
del s1.currency deletes the instance attribute. After that, the lookup of s1.currency falls back to the class.
Solution
class Store: currency = "USD"
def __init__(self, store_id: str): self.store_id = store_id
s1 = Store("S01")s2 = Store("S02")s1.currency = "EUR"Store.currency = "CAD"print(s1.currency, s2.currency, Store.currency)print(vars(s1))print(vars(s2))del s1.currencyprint(s1.currency)
assert "currency" not in vars(s1)assert s1.currency == s2.currency == "CAD"EUR CAD CAD{'store_id': 'S01', 'currency': 'EUR'}{'store_id': 'S02'}CADHow it works:
s1.currency = "EUR"creates an instance attribute ons1. It shadows the class attribute fors1only.Store.currency = "CAD"changes the class attribute.s2has no attribute of its own, so it seesCAD.s1still sees its ownEUR.vars(s1)shows both instance attributes ofs1.vars(s2)shows onlystore_id;currencyis not stored ons2at all.- After
del s1.currency, the instance attribute is gone, sos1.currencyfalls back to the class value,CAD.
Alternative: check where a value lives with "currency" in vars(s1). It is True only for an instance attribute, while hasattr(s1, "currency") is True in both cases.
M18-W03 · Fix the bug: the missing self
Section titled “M18-W03 · Fix the bug: the missing self”Fix the bug: this class for data/stores.csv should report the revenue per square meter of a store. Store S01 (Chicago, 2,850 m²) had a revenue of 412,560.25 USD in a quarter. The call raises a TypeError. Find the two mistakes and fix them.
S01 Chicago: 144.76 USD/m²class StoreRecord: def __init__(self, store_id: str, city: str, size_sqm: int): self.store_id = store_id self.city = city self.size_sqm = size_sqm
def revenue_per_sqm(revenue: float) -> float: return round(revenue / size_sqm, 2)
chicago = StoreRecord("S01", "Chicago", 2850)rate = chicago.revenue_per_sqm(412_560.25)print(f"{chicago.store_id} {chicago.city}: {rate} USD/m²")# TODO: fix the method so that the call worksHint 1
Run the code and read the last line of the traceback. How many arguments does Python say it passed?
Hint 2
After you add the first parameter, the next run raises a NameError. Inside a method, how do you reach an attribute of the instance?
Solution
class StoreRecord: def __init__(self, store_id: str, city: str, size_sqm: int): self.store_id = store_id self.city = city self.size_sqm = size_sqm
def revenue_per_sqm(self, revenue: float) -> float: return round(revenue / self.size_sqm, 2)
chicago = StoreRecord("S01", "Chicago", 2850)rate = chicago.revenue_per_sqm(412_560.25)print(f"{chicago.store_id} {chicago.city}: {rate} USD/m²")
assert chicago.revenue_per_sqm(2850) == 1.0assert StoreRecord.revenue_per_sqm(chicago, 5700) == 2.0S01 Chicago: 144.76 USD/m²How it works:
- Bug 1: the method had no
self. Python passes the instance plus412_560.25, which is 2 arguments for 1 parameter:TypeError: StoreRecord.revenue_per_sqm() takes 1 positional argument but 2 were given. - Bug 2:
size_sqmalone is a local or global name, and neither exists. The value lives on the instance:self.size_sqm. - The second assert shows what
chicago.revenue_per_sqm(5700)really does: it calls the function in the class withchicagoas the first argument.
Alternative: if the method is only a formula over an attribute and an argument, it is fine as a method. If you need the same formula for raw numbers too, write a module function revenue_per_sqm(revenue, size_sqm) and call it from the method.
M18-W04 · A read-only property
Section titled “M18-W04 · A read-only property”Write a class House with house_id, sqft and price. Add a read-only property price_per_sqft that returns the price divided by the area, rounded to 2 decimals. Use house H0001 from data/houses.csv (2,420 sqft, 1,097,500 USD). Print the value, change the price to 1,150,000 and print it again. Then show that h.price_per_sqft = 0 fails, by catching the AttributeError and printing its message.
H0001 453.51H0001 475.21error: property 'price_per_sqft' of 'House' object has no setterclass House: def __init__(self, house_id: str, sqft: int, price: int): self.house_id = house_id self.sqft = sqft self.price = price
# TODO: a property price_per_sqft
h = House("H0001", 2420, 1_097_500)# TODO: print the property, change the price, print again# TODO: try to assign the property and print the error messageHint 1
Write a method price_per_sqft(self) and put @property on the line above it. Read it without parentheses: h.price_per_sqft.
Hint 2
Put the assignment in try: and catch AttributeError as exc. print(exc) shows the message.
Solution
class House: def __init__(self, house_id: str, sqft: int, price: int): self.house_id = house_id self.sqft = sqft self.price = price
@property def price_per_sqft(self) -> float: return round(self.price / self.sqft, 2)
h = House("H0001", 2420, 1_097_500)print(h.house_id, h.price_per_sqft)h.price = 1_150_000print(h.house_id, h.price_per_sqft)try: h.price_per_sqft = 0except AttributeError as exc: print("error:", exc)
assert h.price_per_sqft == round(1_150_000 / 2420, 2)assert "price_per_sqft" not in vars(h)H0001 453.51H0001 475.21error: property 'price_per_sqft' of 'House' object has no setterHow it works:
@propertyturns the method into a property on the class.h.price_per_sqftruns the method and returns its value.- The value is computed on every read, so it follows the price change at once.
- The property has no setter, so an assignment raises an
AttributeErrorthat names the property and the class. - The second assert shows that nothing is stored on the instance under that name.
Alternative: a method price_per_sqft() gives the same numbers. The property reads like a column of the data, which is how analysts think of it.
M18-W05 · An alternative constructor from a CSV line
Section titled “M18-W05 · An alternative constructor from a CSV line”Write a class Store with store_id, city, region, size_sqm (an int) and opened (a str). Add a class method from_csv_line(line) that splits one line of data/stores.csv on commas and returns a Store. Build S01 and S02 from the two lines in the starter and print them.
S01 Chicago (North): 2850 m², opened 2009-03-14S02 Minneapolis (North): 1950 m², opened 2012-08-01class Store: def __init__( self, store_id: str, city: str, region: str, size_sqm: int, opened: str ): self.store_id = store_id self.city = city self.region = region self.size_sqm = size_sqm self.opened = opened
# TODO: a class method from_csv_line(cls, line)
lines = [ "S01,Chicago,North,2850,2009-03-14\n", "S02,Minneapolis,North,1950,2012-08-01\n",]# TODO: build one Store per line and print "S01 Chicago (North): 2850 m², opened 2009-03-14"Hint 1
Put @classmethod above the method and name the first parameter cls. line.strip().split(",") gives a list of 5 strings.
Hint 2
Unpack the list into 5 names, convert size_sqm with int(), then return cls(store_id, city, region, int(size_sqm), opened).
Solution
from typing import Self
class Store: def __init__( self, store_id: str, city: str, region: str, size_sqm: int, opened: str ): self.store_id = store_id self.city = city self.region = region self.size_sqm = size_sqm self.opened = opened
@classmethod def from_csv_line(cls, line: str) -> Self: store_id, city, region, size_sqm, opened = line.strip().split(",") return cls(store_id, city, region, int(size_sqm), opened)
lines = [ "S01,Chicago,North,2850,2009-03-14\n", "S02,Minneapolis,North,1950,2012-08-01\n",]stores = [Store.from_csv_line(line) for line in lines]for s in stores: print(f"{s.store_id} {s.city} ({s.region}): {s.size_sqm} m², opened {s.opened}")
assert isinstance(stores[0], Store)assert stores[1].size_sqm == 1950 and isinstance(stores[1].size_sqm, int)S01 Chicago (North): 2850 m², opened 2009-03-14S02 Minneapolis (North): 1950 m², opened 2012-08-01How it works:
Store.from_csv_line(line)passes the class asclsand the text asline.strip()removes the line break, andsplit(",")cuts the line into its 5 fields.cls(...)is the normal constructor call, so the object goes through__init__with clean, typed values.Selfsays that the method returns an instance of the class it is called on.
Alternative: for a whole file, read it with csv.DictReader and write from_csv_row(cls, row: dict[str, str]), which reads the fields by name. That is safer when the column order can change, and it handles quoted commas.
M18-W06 · Static methods for unit conversion
Section titled “M18-W06 · Static methods for unit conversion”Write a class Temperature that groups two static methods: c_to_f(celsius) and f_to_c(fahrenheit), both rounded to 2 decimals. Convert the S1 reading 20.21 °C to °F, convert 98.6 °F to °C, and show that the round trip gives back 20.21. Call one method through the class and one through an instance, to see that both work.
S1: 68.38 °FBody temperature: 37.0 °CRound trip: 20.21class Temperature: # TODO: two static methods c_to_f and f_to_c ...
# TODO: print the three resultsHint 1
Put @staticmethod above each def. A static method has no self or cls parameter: def c_to_f(celsius: float) -> float:.
Hint 2
°F = °C × 9 / 5 + 32 and °C = (°F − 32) × 5 / 9. Call them as Temperature.c_to_f(20.21) or Temperature().f_to_c(98.6).
Solution
class Temperature: @staticmethod def c_to_f(celsius: float) -> float: return round(celsius * 9 / 5 + 32, 2)
@staticmethod def f_to_c(fahrenheit: float) -> float: return round((fahrenheit - 32) * 5 / 9, 2)
s1_f = Temperature.c_to_f(20.21)print("S1:", s1_f, "°F")print("Body temperature:", Temperature().f_to_c(98.6), "°C")print("Round trip:", Temperature.f_to_c(s1_f))
assert Temperature.c_to_f(100) == 212.0assert Temperature.f_to_c(Temperature.c_to_f(20.21)) == 20.21S1: 68.38 °FBody temperature: 37.0 °CRound trip: 20.21How it works:
@staticmethodstops Python from passing the instance or the class. The methods are plain functions stored in the class namespace.Temperature.c_to_f(20.21)andTemperature().f_to_c(98.6)both work. Through an instance, Python still passes noself.- The round trip gives 20.21 back, because 68.38 °F converts to 20.2111… °C, which rounds to 20.21.
Alternative: two module-level functions c_to_f and f_to_c in a module units.py do the same job, and many projects prefer them: from units import c_to_f. A class of only static methods is mainly a way to group names; a module does that too.
M18-W07 · Predict the output: name mangling
Section titled “M18-W07 · Predict the output: name mangling”Predict the output: an API client keeps an internal note and a secret key. Write down what each print shows. Then run the code and compare.
Acceptance criteria:
- Write your prediction for all four lines before you run the code.
- Run the code. Your prediction matches the Output in the solution, line by line.
- You can explain why
hasattr(client, "__key")andhasattr(client, "_ApiClient__key")differ.
class ApiClient: def __init__(self, key: str): self._note = "rate limit 60/min" self.__key = key
def masked_key(self) -> str: return self.__key[:4] + "****"
client = ApiClient("sk-1234567890")print(sorted(vars(client)))print(client.masked_key())print(hasattr(client, "__key"), hasattr(client, "_ApiClient__key"))print(client._note)# TODO: write your prediction for each print before you run itHint 1
Inside the class body, __key is renamed. What is the new name, for a class called ApiClient?
Hint 2
hasattr takes the name as a string. Strings are not renamed. One underscore (_note) is never renamed.
Solution
class ApiClient: def __init__(self, key: str): self._note = "rate limit 60/min" self.__key = key
def masked_key(self) -> str: return self.__key[:4] + "****"
client = ApiClient("sk-1234567890")print(sorted(vars(client)))print(client.masked_key())print(hasattr(client, "__key"), hasattr(client, "_ApiClient__key"))print(client._note)
assert "_ApiClient__key" in vars(client)assert client._ApiClient__key == "sk-1234567890"['_ApiClient__key', '_note']sk-1****False Truerate limit 60/minHow it works:
- Inside the class,
self.__keyis rewritten toself._ApiClient__key, in__init__and inmasked_key. So the method finds the value. sorted(vars(client))sorts the attribute names._ApiClient__keycomes before_note, becauseAsorts beforen.hasattr(client, "__key")looks for the literal name__key, which does not exist. The mangled name does._notehas one underscore. It is internal by convention, but Python does not rename it, and the outside code can read it.
Alternative: never rely on mangling to protect a secret. The key is still readable as client._ApiClient__key. Real code keeps secrets out of objects that get printed or logged, and reads them from environment variables (module 16).
M18-W08 · Fix the bug: the counter that never counts
Section titled “M18-W08 · Fix the bug: the counter that never counts”Fix the bug: every Forecast object should get an id from a shared counter, and Forecast.created should count the objects. After three forecasts, the class counter still says 0, and every forecast gets id 1.
1 S01 72 S02 73 S01 28created: 3class Forecast: created = 0
def __init__(self, store_id: str, horizon_days: int): self.store_id = store_id self.horizon_days = horizon_days self.created += 1 self.forecast_id = self.created
forecasts = [Forecast("S01", 7), Forecast("S02", 7), Forecast("S01", 28)]for f in forecasts: print(f.forecast_id, f.store_id, f.horizon_days)print("created:", Forecast.created)# TODO: fix __init__ so that the ids are 1, 2, 3 and Forecast.created is 3Hint 1
Print vars(forecasts[0]). Which attribute did self.created += 1 create?
Hint 2
Change the counter through the class, not through self.
Solution
class Forecast: created = 0
def __init__(self, store_id: str, horizon_days: int): self.store_id = store_id self.horizon_days = horizon_days Forecast.created += 1 self.forecast_id = Forecast.created
forecasts = [Forecast("S01", 7), Forecast("S02", 7), Forecast("S01", 28)]for f in forecasts: print(f.forecast_id, f.store_id, f.horizon_days)print("created:", Forecast.created)
assert [f.forecast_id for f in forecasts] == [1, 2, 3]assert "created" not in vars(forecasts[0])1 S01 72 S02 73 S01 28created: 3How it works:
- In the bug,
self.created += 1read the class value 0 and wrotecreated = 1as a new instance attribute. Each object got its owncreatedof 1, and the class counter stayed at 0. Forecast.created += 1changes the one value in the class namespace.self.forecast_id = Forecast.createdcopies the current count into an instance attribute, so each forecast keeps its own id.- The second assert proves that no instance attribute
createdwas made.
Alternative: type(self).created += 1 also works for this class; module 19 shows how it behaves with subclasses. For ids that must be unique across processes, use uuid.uuid4() instead of a counter.
M18-C01 · Customers with validated charges
Section titled “M18-C01 · Customers with validated charges”Write a class Customer for data/customers.csv with customer_id, plan and monthly_charges. Make monthly_charges a property with a setter that raises TypeError for a value that is not an int or float (reject bool) and ValueError for a value of 0 or less. Add a class method from_csv_row(row). Load all 5,000 customers, print the mean monthly charges per plan in alphabetical order, then show the two errors for -5.0 and "30.93".
basic 2028 customers, mean 39.27 USDpremium 990 customers, mean 98.59 USDstandard 1982 customers, mean 64.04 USDValueError: monthly_charges must be > 0, got -5.0TypeError: monthly_charges must be a number, got '30.93'import csvfrom typing import Self
class Customer: def __init__(self, customer_id: str, plan: str, monthly_charges: float): self.customer_id = customer_id self.plan = plan self.monthly_charges = monthly_charges # should run the setter
# TODO: the monthly_charges property and its setter (store the value in _monthly_charges) # TODO: the class method from_csv_row
# TODO: load data/customers.csv into a list of Customer objects# TODO: one line per plan, sorted: "basic 2028 customers, mean 39.27 USD"# TODO: try Customer("C99999", "basic", -5.0) and Customer("C99999", "basic", "30.93")Hint 1
The getter returns self._monthly_charges. The setter is decorated with @monthly_charges.setter and has the same name.
Hint 2
Check the type first: isinstance(value, bool) or not isinstance(value, (int, float)). Group the customers with a dict of lists, keyed by plan.
Solution
import csvfrom typing import Self
class Customer: def __init__(self, customer_id: str, plan: str, monthly_charges: float): self.customer_id = customer_id self.plan = plan self.monthly_charges = monthly_charges # runs the setter
@property def monthly_charges(self) -> float: return self._monthly_charges
@monthly_charges.setter def monthly_charges(self, value: float) -> None: if isinstance(value, bool) or not isinstance(value, (int, float)): raise TypeError(f"monthly_charges must be a number, got {value!r}") if value <= 0: raise ValueError(f"monthly_charges must be > 0, got {value}") self._monthly_charges = float(value)
@classmethod def from_csv_row(cls, row: dict[str, str]) -> Self: return cls(row["customer_id"], row["plan"], float(row["monthly_charges"]))
with open("data/customers.csv", newline="", encoding="utf-8") as f: customers = [Customer.from_csv_row(row) for row in csv.DictReader(f)]
by_plan: dict[str, list[float]] = {}for c in customers: by_plan.setdefault(c.plan, []).append(c.monthly_charges)for plan in sorted(by_plan): charges = by_plan[plan] mean = sum(charges) / len(charges) print(f"{plan:<8} {len(charges):>5} customers, mean {mean:6.2f} USD")
for bad in (-5.0, "30.93"): try: Customer("C99999", "basic", bad) except (TypeError, ValueError) as exc: print(f"{type(exc).__name__}: {exc}")
assert len(customers) == 5000assert sum(len(v) for v in by_plan.values()) == 5000assert all(c.monthly_charges > 0 for c in customers)basic 2028 customers, mean 39.27 USDpremium 990 customers, mean 98.59 USDstandard 1982 customers, mean 64.04 USDValueError: monthly_charges must be > 0, got -5.0TypeError: monthly_charges must be a number, got '30.93'How it works:
self.monthly_charges = monthly_chargesin__init__runs the setter, so each new customer is checked, including all 5,000 from the file.- The setter checks the type first, then the range. A text value such as
"30.93"is a type error, even though it looks like a number. - The setter stores a
floatin_monthly_charges, so the getter always returns the same type. setdefault(plan, [])returns the list for a plan and creates it the first time (module 04). The means rise with the plan: premium costs the most.
Alternative: pydantic (see the lesson) does the same checks with monthly_charges: float = Field(gt=0). Note one difference: pydantic converts "30.93" to 30.93 by default, while this setter rejects it. Decide which behavior your data needs.
M18-C02 · Fix the bug: selectors that share their features
Section titled “M18-C02 · Fix the bug: selectors that share their features”Fix the bug: a FeatureSelector keeps the names of the features that a model will use. Two selectors, one for a price model and one for a quality model on data/houses.csv, show each other’s features. Fix the class so that each selector has its own list, and keep max_features as a shared default that one selector can override.
price ['sqft', 'neighborhood'] 3quality ['condition', 'year_built'] 2class FeatureSelector: max_features = 3 # shared default selected = []
def __init__(self, name: str): self.name = name
def add(self, feature: str) -> None: if len(self.selected) >= self.max_features: raise ValueError(f"{self.name}: at most {self.max_features} features") self.selected.append(feature)
price = FeatureSelector("price")quality = FeatureSelector("quality")price.add("sqft")price.add("neighborhood")quality.max_features = 2 # this selector allows only 2quality.add("condition")quality.add("year_built")print(price.name, price.selected, price.max_features)print(quality.name, quality.selected, quality.max_features)# TODO: fix the class so that the two lists are separateHint 1
Run the starter. Which call fails, and why does quality already have features when it adds its first one?
Hint 2
One of the two class attributes is fine as a class attribute. The other one must become an instance attribute, created in __init__.
Solution
class FeatureSelector: max_features = 3 # shared default; an instance can override it
def __init__(self, name: str): self.name = name self.selected: list[str] = [] # one list per selector
def add(self, feature: str) -> None: if len(self.selected) >= self.max_features: raise ValueError(f"{self.name}: at most {self.max_features} features") self.selected.append(feature)
price = FeatureSelector("price")quality = FeatureSelector("quality")price.add("sqft")price.add("neighborhood")quality.max_features = 2 # this selector allows only 2quality.add("condition")quality.add("year_built")print(price.name, price.selected, price.max_features)print(quality.name, quality.selected, quality.max_features)
assert price.selected is not quality.selectedassert "max_features" not in vars(price) and vars(quality)["max_features"] == 2price ['sqft', 'neighborhood'] 3quality ['condition', 'year_built'] 2How it works:
- In the starter,
selectedis one list in the class namespace.price.addputs two names in it. Whenqualityadds its first feature, the shared list already holds those 2 names, soadd("condition")raisesValueError: quality: at most 2 features. - The fix creates
self.selectedin__init__, so each selector gets a new, empty list. max_featuresis an immutable number, so it is safe as a class attribute.quality.max_features = 2creates an instance attribute that overrides the default forqualityonly.- The asserts check both facts: two separate lists, and one override stored on
qualityalone.
Alternative: pass the limit to the initializer: def __init__(self, name, max_features=3), and store self.max_features = max_features. This is clearer when most instances change the value; the class attribute is fine when most keep the default.
M18-C03 · Refactor: a revenue tracker class
Section titled “M18-C03 · Refactor: a revenue tracker class”Refactor: the procedural code in the starter sums revenue per store from the first 1,000 lines of data/sales.csv. Turn it into a class RevenueTracker with a method add(store_id, revenue), a read-only property total, and a method top(n) that returns the n best stores as (store_id, revenue) pairs with the revenue rounded to 2 decimals. The output must stay the same.
total: 178726.0S07 26674.22S10 24825.31S04 23021.06import csv
totals = {}
def add_sale(totals, store_id, revenue): totals[store_id] = totals.get(store_id, 0.0) + revenue
def top_stores(totals, n): ranked = sorted(totals.items(), key=lambda kv: kv[1], reverse=True) return [(s, round(r, 2)) for s, r in ranked[:n]]
with open("data/sales.csv", newline="", encoding="utf-8") as f: for i, row in enumerate(csv.DictReader(f)): if i == 1000: break add_sale(totals, row["store_id"], float(row["revenue"]))
print("total:", round(sum(totals.values()), 2))for store_id, revenue in top_stores(totals, 3): print(store_id, revenue)# TODO: replace the dict and the two functions with a RevenueTracker classHint 1
The global totals dict becomes an instance attribute created in __init__. Each function becomes a method, and its totals parameter becomes self._totals.
Hint 2
total is a property that returns round(sum(self._totals.values()), 2). Read the file with itertools.islice(reader, 1000) to take the first 1,000 rows.
Solution
import csvfrom itertools import islice
class RevenueTracker: """Revenue per store, built one sale at a time."""
def __init__(self): self._totals: dict[str, float] = {}
def add(self, store_id: str, revenue: float) -> None: self._totals[store_id] = self._totals.get(store_id, 0.0) + revenue
@property def total(self) -> float: return round(sum(self._totals.values()), 2)
def top(self, n: int) -> list[tuple[str, float]]: ranked = sorted(self._totals.items(), key=lambda kv: kv[1], reverse=True) return [(store_id, round(revenue, 2)) for store_id, revenue in ranked[:n]]
tracker = RevenueTracker()with open("data/sales.csv", newline="", encoding="utf-8") as f: for row in islice(csv.DictReader(f), 1000): tracker.add(row["store_id"], float(row["revenue"]))
print("total:", tracker.total)for store_id, revenue in tracker.top(3): print(store_id, revenue)
assert len(tracker.top(3)) == 3assert tracker.top(1)[0] == tracker.top(3)[0]assert tracker.total >= sum(revenue for _, revenue in tracker.top(3))total: 178726.0S07 26674.22S10 24825.31S04 23021.06How it works:
- The state (
_totals) moved into the object. It has one underscore, because callers should useadd,totalandtop, not the dict. - The global variable is gone. Two trackers, for example one per month, no longer share data by accident.
totalis a property: it reads like a value and is always in sync with the sales added so far.islice(reader, 1000)(module 10) stops after 1,000 rows, so theif i == 1000: breaklogic is gone.
Alternative: collections.Counter (module 09) already sums values per key and has most_common(n). self._totals = Counter() and self._totals[store_id] += revenue make the class shorter. The class still adds value: it hides the choice of Counter behind add and top.
M18-C04 · Validate a training configuration
Section titled “M18-C04 · Validate a training configuration”Write a class TrainConfig with three validated properties: learning_rate (a number with 0 < lr ≤ 1), epochs (an int of at least 1, not a bool) and batch_size (an int that is a power of 2, such as 32 or 64). Wrong types raise TypeError, bad values raise ValueError. Create a valid config, then print the error for each bad config in the starter.
0.05 20 64{'learning_rate': 0} -> ValueError: learning_rate must be in (0, 1], got 0{'learning_rate': 1.5} -> ValueError: learning_rate must be in (0, 1], got 1.5{'epochs': True} -> TypeError: epochs must be an int, got bool{'epochs': 0} -> ValueError: epochs must be >= 1, got 0{'batch_size': 48} -> ValueError: batch_size must be a power of 2, got 48class TrainConfig: def __init__(self, learning_rate: float = 0.01, epochs: int = 10, batch_size: int = 32): self.learning_rate = learning_rate self.epochs = epochs self.batch_size = batch_size
# TODO: three properties with setters
cfg = TrainConfig(learning_rate=0.05, epochs=20, batch_size=64)print(cfg.learning_rate, cfg.epochs, cfg.batch_size)bad_configs = [ {"learning_rate": 0}, {"learning_rate": 1.5}, {"epochs": True}, {"epochs": 0}, {"batch_size": 48},]# TODO: for each bad config, print "<kwargs> -> <ErrorType>: <message>"Hint 1
Write one getter and one setter per property, and store each value under a name with one underscore: _learning_rate, _epochs, _batch_size.
Hint 2
A positive int n is a power of 2 when n & (n - 1) == 0. The & operator compares the bits of two integers. You can also test n in {1, 2, 4, 8, 16, 32, 64, 128, 256, 512}.
Solution
class TrainConfig: def __init__( self, learning_rate: float = 0.01, epochs: int = 10, batch_size: int = 32 ): self.learning_rate = learning_rate self.epochs = epochs self.batch_size = batch_size
@staticmethod def _check_int(name: str, value: int) -> None: if isinstance(value, bool) or not isinstance(value, int): raise TypeError(f"{name} must be an int, got {type(value).__name__}")
@property def learning_rate(self) -> float: return self._learning_rate
@learning_rate.setter def learning_rate(self, value: float) -> None: if isinstance(value, bool) or not isinstance(value, (int, float)): raise TypeError(f"learning_rate must be a number, got {value!r}") if not 0 < value <= 1: raise ValueError(f"learning_rate must be in (0, 1], got {value}") self._learning_rate = value
@property def epochs(self) -> int: return self._epochs
@epochs.setter def epochs(self, value: int) -> None: self._check_int("epochs", value) if value < 1: raise ValueError(f"epochs must be >= 1, got {value}") self._epochs = value
@property def batch_size(self) -> int: return self._batch_size
@batch_size.setter def batch_size(self, value: int) -> None: self._check_int("batch_size", value) if value < 1 or value & (value - 1) != 0: raise ValueError(f"batch_size must be a power of 2, got {value}") self._batch_size = value
cfg = TrainConfig(learning_rate=0.05, epochs=20, batch_size=64)print(cfg.learning_rate, cfg.epochs, cfg.batch_size)bad_configs = [ {"learning_rate": 0}, {"learning_rate": 1.5}, {"epochs": True}, {"epochs": 0}, {"batch_size": 48},]errors = []for kwargs in bad_configs: try: TrainConfig(**kwargs) except (TypeError, ValueError) as exc: errors.append(type(exc).__name__) print(f"{kwargs} -> {type(exc).__name__}: {exc}")
assert errors == ["ValueError", "ValueError", "TypeError", "ValueError", "ValueError"]assert TrainConfig().batch_size == 320.05 20 64{'learning_rate': 0} -> ValueError: learning_rate must be in (0, 1], got 0{'learning_rate': 1.5} -> ValueError: learning_rate must be in (0, 1], got 1.5{'epochs': True} -> TypeError: epochs must be an int, got bool{'epochs': 0} -> ValueError: epochs must be >= 1, got 0{'batch_size': 48} -> ValueError: batch_size must be a power of 2, got 48How it works:
- Each assignment in
__init__runs a setter, so a bad value fails at construction. - The static method
_check_intholds the type check that two setters share. It needs neither the instance nor the class. 0 < value <= 1is a chained comparison (module 01). It rejects 0 and 1.5.48 & 47is not 0, because 48 (binary 110000) has two 1 bits. A power of 2 has exactly one 1 bit, son & (n - 1)clears it and gives 0.
Alternative: with many fields like this, a dataclass with a __post_init__ check (module 21) or a pydantic model is shorter. Properties are the right tool when one value must be checked on every later assignment too.
M18-C05 · Predict the output: a game entity
Section titled “M18-C05 · Predict the output: a game entity”Predict the output: this class from a small 2D game mixes a class attribute, instance attributes, a class method, a static method and a property. Write down what each print shows. Then run the code and compare.
Acceptance criteria:
- Write your prediction for all five lines before you run the code.
- Run the code. Your prediction matches the Output in the solution, line by line.
- For each line, you can name the kind of attribute or method that produced it.
from typing import Self
class Player: max_health = 100 count = 0
def __init__(self, name: str, x: int = 0, y: int = 0): self.name = name self.x, self.y = x, y self.health = self.max_health Player.count += 1
@classmethod def spawn_at_origin(cls, name: str) -> Self: return cls(name)
@staticmethod def clamp(value: int, low: int, high: int) -> int: return max(low, min(value, high))
@property def is_alive(self) -> bool: return self.health > 0
def take_damage(self, amount: int) -> None: self.health = self.clamp(self.health - amount, 0, self.max_health)
def move(self, dx: int, dy: int) -> None: self.x, self.y = self.x + dx, self.y + dy
hero = Player.spawn_at_origin("hero")orc = Player("orc", x=5, y=2)orc.take_damage(30)hero.take_damage(250)print(hero.health, hero.is_alive, orc.health, orc.is_alive)Player.max_health = 150print(Player("elf").health, orc.health)orc.move(-2, 4)print(orc.x, orc.y)print(Player.count, Player.clamp(7, 0, 5))print(sorted(vars(orc)))# TODO: write your prediction for each print before you run itHint 1
clamp keeps a value between low and high. What is clamp(100 - 250, 0, 100)?
Hint 2
self.health = self.max_health copies the class value into the instance when the player is created. Does a later change to Player.max_health change that copy?
Solution
from typing import Self
class Player: max_health = 100 count = 0
def __init__(self, name: str, x: int = 0, y: int = 0): self.name = name self.x, self.y = x, y self.health = self.max_health Player.count += 1
@classmethod def spawn_at_origin(cls, name: str) -> Self: return cls(name)
@staticmethod def clamp(value: int, low: int, high: int) -> int: return max(low, min(value, high))
@property def is_alive(self) -> bool: return self.health > 0
def take_damage(self, amount: int) -> None: self.health = self.clamp(self.health - amount, 0, self.max_health)
def move(self, dx: int, dy: int) -> None: self.x, self.y = self.x + dx, self.y + dy
hero = Player.spawn_at_origin("hero")orc = Player("orc", x=5, y=2)orc.take_damage(30)hero.take_damage(250)print(hero.health, hero.is_alive, orc.health, orc.is_alive)Player.max_health = 150print(Player("elf").health, orc.health)orc.move(-2, 4)print(orc.x, orc.y)print(Player.count, Player.clamp(7, 0, 5))print(sorted(vars(orc)))
assert hero.health == 0 and not hero.is_aliveassert "max_health" not in vars(orc)0 False 70 True150 703 63 5['health', 'name', 'x', 'y']How it works:
heroloses 250 of 100 health.clamp(-150, 0, 100)gives 0, so the hero is dead. The orc has 100 − 30 = 70.- The elf is created after
Player.max_healthbecame 150, so it starts with 150. The orc keeps its stored 70:healthis an instance attribute, copied once in__init__. movechanges the orc’s own position: (5 − 2, 2 + 4) = (3, 6).- Three players were created (hero, orc, elf). The class method
spawn_at_origincallscls(name), so it also runs__init__and counts.clamp(7, 0, 5)is 5. vars(orc)holds only instance data.max_health,countand the methods live in the class.
Alternative: if every player should always use the current maximum, do not copy it: compute health as a fraction of self.max_health, or check the limit only when you heal. This is the same choice as a stored attribute versus a property.
M18-C06 · Interpret: where does each attribute live?
Section titled “M18-C06 · Interpret: where does each attribute live?”Interpret: a teammate’s Scaler class behaves strangely. Run the code in the starter, read its output and answer the three questions in comments. Then prove each answer with an assert.
- Why does
b.fittedprintTrue, althoughb.fitwas never called? - Why does
a.meanprint22.05butb.meanprint0.0? - Which single change makes
b.fittedFalse? Write the fixed class asFixedScaler, fit one instance, create a second one and print thefittedvalue of both.
22.05 True0.0 True['mean'] []True Falsefrom typing import Self
class Scaler: mean = 0.0 state = {"fitted": False}
def fit(self, values: list[float]) -> Self: self.mean = round(sum(values) / len(values), 2) self.state["fitted"] = True return self
@property def fitted(self) -> bool: return self.state["fitted"]
a = Scaler().fit([20.21, 21.47, 24.47]) # S1 temperaturesb = Scaler()print(a.mean, a.fitted)print(b.mean, b.fitted)print(sorted(vars(a)), sorted(vars(b)))# TODO: answer the three questions in comments# TODO: add one assert per answer# TODO: write FixedScaler, then print(fixed_a.fitted, fixed_b.fitted)Hint 1
Look at the last line of output. Which names are in vars(a)? Which are in vars(b)?
Hint 2
self.mean = ... is an assignment. self.state["fitted"] = True changes an item of a dict that self.state finds. Which one creates an instance attribute?
Solution
from typing import Self
class Scaler: mean = 0.0 state = {"fitted": False}
def fit(self, values: list[float]) -> Self: self.mean = round(sum(values) / len(values), 2) self.state["fitted"] = True return self
@property def fitted(self) -> bool: return self.state["fitted"]
a = Scaler().fit([20.21, 21.47, 24.47]) # S1 temperaturesb = Scaler()print(a.mean, a.fitted)print(b.mean, b.fitted)print(sorted(vars(a)), sorted(vars(b)))
# 1. state is one dict on the class. a.fit() changed it in place, so every Scaler# (b too) now reads fitted = True.assert a.state is b.state is Scaler.state# 2. self.mean = ... is an assignment, so it created an instance attribute on a.# b has none and falls back to the class value 0.0.assert "mean" in vars(a) and "mean" not in vars(b)# 3. Create the dict per instance in __init__.
class FixedScaler: mean = 0.0
def __init__(self): self.state = {"fitted": False} # one dict per instance
def fit(self, values: list[float]) -> Self: self.mean = round(sum(values) / len(values), 2) self.state["fitted"] = True return self
@property def fitted(self) -> bool: return self.state["fitted"]
fixed_a = FixedScaler().fit([20.21, 21.47, 24.47])fixed_b = FixedScaler()print(fixed_a.fitted, fixed_b.fitted)assert fixed_a.fitted and not fixed_b.fittedassert fixed_a.state is not fixed_b.state22.05 True0.0 True['mean'] []True FalseHow it works:
- The two class attributes behave differently because the code uses them differently.
meanis rebound with=, which creates an instance attribute.stateis changed in place, which never creates one. vars(a)contains onlymean.vars(b)is empty. Sob.fittedreads the one shared dict, whicha.fit()already changed.FixedScalerisScalerwith one added__init__that gives each instance its own dict. Nowfixed_a.fit()changes only the dict offixed_a, and the last assert proves that the two dicts are separate objects.
Alternative: drop the dict. Set the learned attribute self.mean_ = ... only in fit, and make fitted return hasattr(self, "mean_"). This is the scikit-learn convention, and it has no shared state at all.
M18-C07 · Choose and justify: which kind of method?
Section titled “M18-C07 · Choose and justify: which kind of method?”Choose and justify: a SensorLog class holds the readings of one sensor from data/sensors.csv. It needs four helpers. For each one, choose an instance method, a property, a class method or a static method, and write one comment that justifies the choice. Then implement the class and run it on sensor S3 for 2024-05-01.
parse_time(text): turn"2024-05-01T13:30:00"into the minutes since midnight (810).from_csv(path, sensor_id, day): build aSensorLogfrom the file.mean_temperature: the mean of the non-blank temperatures of this log, rounded to 2 decimals.readings_between(start, end): the temperatures of the readings withstart <= minutes < end.
S3 144 readingsmean: 21.2903:00-04:00: [19.18, 19.52, 19.63, 19.22, 19.25, 19.07]import csv
class SensorLog: def __init__(self, sensor_id: str, minutes: list[int], temps: list[float | None]): self.sensor_id = sensor_id self.minutes = minutes # minutes since midnight, one per reading self.temps = temps # temperature_c, None for a blank cell
# TODO: parse_time, from_csv, mean_temperature, readings_between # TODO: one comment per helper that justifies its kind
log = SensorLog.from_csv("data/sensors.csv", sensor_id="S3", day="2024-05-01")# TODO: print the number of readings, the mean temperature and the readings 03:00-04:00Hint 1
Ask two questions per helper: does it need the data of one log (self)? Does it create a new log (cls)?
Hint 2
parse_time needs neither. from_csv creates an instance. mean_temperature takes no arguments and reads like a value. readings_between takes arguments and reads the log.
Solution
import csvfrom typing import Self
class SensorLog: def __init__(self, sensor_id: str, minutes: list[int], temps: list[float | None]): self.sensor_id = sensor_id self.minutes = minutes # minutes since midnight, one per reading self.temps = temps # temperature_c, None for a blank cell
@staticmethod def parse_time(text: str) -> int: # Static: a pure text-to-number helper; needs no log and no class. hours, minutes = text[11:13], text[14:16] return int(hours) * 60 + int(minutes)
@classmethod def from_csv(cls, path: str, sensor_id: str, day: str) -> Self: # Class method: an alternative constructor; it creates a new log. minutes, temps = [], [] with open(path, newline="", encoding="utf-8") as f: for row in csv.DictReader(f): if row["sensor_id"] == sensor_id and row["timestamp"].startswith(day): minutes.append(cls.parse_time(row["timestamp"])) text = row["temperature_c"] temps.append(float(text) if text else None) return cls(sensor_id, minutes, temps)
@property def mean_temperature(self) -> float: # Property: no arguments, cheap, reads like a value of this log. valid = [t for t in self.temps if t is not None] return round(sum(valid) / len(valid), 2)
def readings_between(self, start: int, end: int) -> list[float | None]: # Instance method: it needs this log's data and takes arguments. return [t for m, t in zip(self.minutes, self.temps) if start <= m < end]
log = SensorLog.from_csv("data/sensors.csv", sensor_id="S3", day="2024-05-01")print(log.sensor_id, len(log.minutes), "readings")print("mean:", log.mean_temperature)print("03:00-04:00:", log.readings_between(180, 240))
assert SensorLog.parse_time("2024-05-01T13:30:00") == 810assert len(log.minutes) == 144 # 24 hours x 6 readings per hourassert len(log.readings_between(180, 240)) == 6S3 144 readingsmean: 21.2903:00-04:00: [19.18, 19.52, 19.63, 19.22, 19.25, 19.07]How it works:
parse_timeworks on a string only, so it is static. The slices[11:13]and[14:16]cut the hour and the minute out of the ISO timestamp.from_csvreads the file and ends withcls(...), the pattern of every alternative constructor.mean_temperatureskips theNonevalues, so a blank cell does not break the mean.readings_betweenpairs each minute with its temperature throughzipand keeps the readings in the half-open interval (module 03). One day of 10-minute readings gives 144 rows.
Alternative: parse_time could use datetime.fromisoformat(text) (module 09), itself a class method, and return dt.hour * 60 + dt.minute. It is slower but rejects malformed text.
M18-C08 · Vibration alerts with shared and per-sensor thresholds
Section titled “M18-C08 · Vibration alerts with shared and per-sensor thresholds”Write a class VibrationMonitor. A class attribute warn_mm_s = 4.5 is the default threshold. Each monitor has a sensor_id and a list of alert timestamps. A method check(timestamp, vibration) adds the timestamp when the vibration is at or above the threshold (skip None), and a property n_alerts returns the count. Run four monitors over the readings of data/sensors.csv from 2024-05-12 on. Sensor S4 is known to be wearing out, so the maintenance team raised its threshold to 6.0 for this report. Print the alerts per sensor and the first S4 alert.
S1: 2 alerts (threshold 4.5)S2: 2 alerts (threshold 4.5)S3: 0 alerts (threshold 4.5)S4: 269 alerts (threshold 6.0)first S4 alert: 2024-05-12T06:30:00import csv
class VibrationMonitor: warn_mm_s = 4.5 # default threshold, mm/s
# TODO: __init__ with sensor_id and an empty list of alerts # TODO: check(timestamp, vibration) and the property n_alerts
# TODO: one monitor per sensor S1-S4, with a threshold of 6.0 for S4 only# TODO: feed every row from 2024-05-12 on to the monitor of its sensor# TODO: print "S1: 2 alerts (threshold 4.5)" etc., then the first S4 alertHint 1
Keep the monitors in a dict keyed by sensor id: monitors = {sid: VibrationMonitor(sid) for sid in ("S1", "S2", "S3", "S4")}.
Hint 2
monitors["S4"].warn_mm_s = 6.0 overrides the threshold for S4 only. ISO timestamps compare correctly as strings: row["timestamp"] >= "2024-05-12".
Solution
import csv
class VibrationMonitor: warn_mm_s = 4.5 # default threshold, mm/s
def __init__(self, sensor_id: str): self.sensor_id = sensor_id self.alerts: list[str] = [] # timestamps of alerts, one list per monitor
def check(self, timestamp: str, vibration: float | None) -> None: if vibration is not None and vibration >= self.warn_mm_s: self.alerts.append(timestamp)
@property def n_alerts(self) -> int: return len(self.alerts)
monitors = {sid: VibrationMonitor(sid) for sid in ("S1", "S2", "S3", "S4")}monitors["S4"].warn_mm_s = 6.0 # override for the worn sensor only
with open("data/sensors.csv", newline="", encoding="utf-8") as f: for row in csv.DictReader(f): if row["timestamp"] >= "2024-05-12": text = row["vibration_mm_s"] value = float(text) if text else None monitors[row["sensor_id"]].check(row["timestamp"], value)
for m in monitors.values(): print(f"{m.sensor_id}: {m.n_alerts} alerts (threshold {m.warn_mm_s})")print("first S4 alert:", monitors["S4"].alerts[0])
assert VibrationMonitor.warn_mm_s == 4.5assert vars(monitors["S4"])["warn_mm_s"] == 6.0assert "warn_mm_s" not in vars(monitors["S1"])S1: 2 alerts (threshold 4.5)S2: 2 alerts (threshold 4.5)S3: 0 alerts (threshold 4.5)S4: 269 alerts (threshold 6.0)first S4 alert: 2024-05-12T06:30:00How it works:
- The default threshold is a class attribute, so three monitors share it. The S4 monitor gets its own instance attribute, which shadows the default.
self.warn_mm_sinsidecheckfollows the normal lookup: the instance first, then the class. The same method uses 6.0 for S4 and 4.5 for the others.- Each monitor creates its own
alertslist in__init__, so the alerts of one sensor never appear in another. - Even with the higher threshold, S4 has far more alerts than the other sensors, which confirms the wear that starts on May 12.
Alternative: pass the threshold to the initializer with the class default as fallback: def __init__(self, sensor_id, warn_mm_s=None) and if warn_mm_s is not None: self.warn_mm_s = warn_mm_s. Then the override is visible where the monitor is created.
M18-C09 · Experiment ids from a class counter
Section titled “M18-C09 · Experiment ids from a class counter”Write a class Experiment that gives each new experiment an id EXP-001, EXP-002 and so on, from a class attribute _next_number. Add a class method reset_ids(start=1) that sets the counter, for example at the start of a test, and a class method from_config(config) that builds an experiment from a dict with the keys "model" and "params". Create three experiments, reset the counter, and create one more.
EXP-001 knn {'n_neighbors': 5}EXP-002 linear {}EXP-003 knn {'n_neighbors': 15}EXP-100 101class Experiment: _next_number = 1 # shared by all experiments
def __init__(self, model: str, params: dict[str, float]): # TODO: take the next id from the class counter, then increase it self.model = model self.params = params
# TODO: class methods reset_ids(start=1) and from_config(config)
runs = [ Experiment("knn", {"n_neighbors": 5}), Experiment("linear", {}), Experiment.from_config({"model": "knn", "params": {"n_neighbors": 15}}),]# TODO: print the id, model and params of each run# TODO: reset the ids to 100 and create one more experimentHint 1
Format the id with f"EXP-{number:03d}". The :03d spec pads the number to 3 digits.
Hint 2
Inside a class method, change the counter with cls._next_number = start. Inside __init__, use type(self)._next_number or Experiment._next_number.
Solution
from typing import Self
class Experiment: _next_number = 1 # shared by all experiments
def __init__(self, model: str, params: dict[str, float]): cls = type(self) self.experiment_id = f"EXP-{cls._next_number:03d}" cls._next_number += 1 self.model = model self.params = dict(params) # a copy: the caller's dict stays separate
@classmethod def reset_ids(cls, start: int = 1) -> None: cls._next_number = start
@classmethod def from_config(cls, config: dict) -> Self: return cls(config["model"], config.get("params", {}))
runs = [ Experiment("knn", {"n_neighbors": 5}), Experiment("linear", {}), Experiment.from_config({"model": "knn", "params": {"n_neighbors": 15}}),]for run in runs: print(run.experiment_id, run.model, run.params)
Experiment.reset_ids(start=100)extra = Experiment("linear", {})print(extra.experiment_id, Experiment._next_number)
assert [r.experiment_id for r in runs] == ["EXP-001", "EXP-002", "EXP-003"]assert "_next_number" not in vars(extra)EXP-001 knn {'n_neighbors': 5}EXP-002 linear {}EXP-003 knn {'n_neighbors': 15}EXP-100 101How it works:
type(self)is the class of the new object. Reading and writingcls._next_numberchanges the one shared counter, not an instance attribute.reset_idsis a class method, because it changes class-wide state and needs no instance.from_configis an alternative constructor. It ends incls(...), so it also takes an id.dict(params)copies the dict. Without the copy, two experiments built from the sameparamsdict would share it, the aliasing problem of module 04.
Alternative: itertools.count(1) stored as a class attribute gives the numbers without += 1: _numbers = count(1) and next(type(self)._numbers). Resetting then means replacing the counter: cls._numbers = count(start).
M18-C10 · A label encoder with learned attributes
Section titled “M18-C10 · A label encoder with learned attributes”ML models need numbers, so text labels are encoded as integers. Write a class LabelEncoder in the scikit-learn style. fit(labels) learns the sorted unique labels into classes_ and returns self. transform(labels) returns the index of each label in classes_. inverse_transform(codes) turns codes back into labels. Both raise NotFittedError (a subclass of ValueError) before fit, and transform raises ValueError for a label it has not seen. Fit it on the plan column of data/customers.csv.
NotFittedError: LabelEncoder is not fitted yet; call fit() first['basic', 'premium', 'standard']['premium', 'standard', 'premium', 'premium', 'basic'] -> [1, 2, 1, 1, 0]['standard', 'basic']ValueError: unseen labels: ['gold']import csv
class NotFittedError(ValueError): """Raised when a model is used before fit()."""
class LabelEncoder: # TODO: fit, transform, inverse_transform and a private _check_fitted ...
with open("data/customers.csv", newline="", encoding="utf-8") as f: plans = [row["plan"] for row in csv.DictReader(f)]# TODO: try transform before fit; then fit, print classes_, encode the first 5 plans# TODO: decode [2, 0] and try to encode "gold"Hint 1
sorted(set(labels)) gives the unique labels in order. Keep a dict from label to index too, so transform is fast: {label: i for i, label in enumerate(self.classes_)}.
Hint 2
The fitted check is hasattr(self, "classes_"). Do not create classes_ in __init__.
Solution
import csvfrom typing import Self
class NotFittedError(ValueError): """Raised when a model is used before fit()."""
class LabelEncoder: def fit(self, labels: list[str]) -> Self: self.classes_ = sorted(set(labels)) self._index = {label: i for i, label in enumerate(self.classes_)} return self
def transform(self, labels: list[str]) -> list[int]: self._check_fitted() unknown = sorted(set(labels) - set(self._index)) if unknown: raise ValueError(f"unseen labels: {unknown}") return [self._index[label] for label in labels]
def inverse_transform(self, codes: list[int]) -> list[str]: self._check_fitted() return [self.classes_[code] for code in codes]
def _check_fitted(self) -> None: if not hasattr(self, "classes_"): raise NotFittedError("LabelEncoder is not fitted yet; call fit() first")
with open("data/customers.csv", newline="", encoding="utf-8") as f: plans = [row["plan"] for row in csv.DictReader(f)]
try: LabelEncoder().transform(plans)except NotFittedError as exc: print("NotFittedError:", exc)
encoder = LabelEncoder().fit(plans)codes = encoder.transform(plans)print(encoder.classes_)print(plans[:5], "->", codes[:5])print(encoder.inverse_transform([2, 0]))try: encoder.transform(["basic", "gold"])except ValueError as exc: print("ValueError:", exc)
assert encoder.inverse_transform(codes) == plansassert isinstance(NotFittedError("x"), ValueError)NotFittedError: LabelEncoder is not fitted yet; call fit() first['basic', 'premium', 'standard']['premium', 'standard', 'premium', 'premium', 'basic'] -> [1, 2, 1, 1, 0]['standard', 'basic']ValueError: unseen labels: ['gold']How it works:
fitsets the learned attributes.classes_is public and ends with_, the scikit-learn sign of a learned value._indexis an internal helper, so it starts with_.fitreturnsself, soLabelEncoder().fit(plans)gives the fitted encoder in one line.transformfirst checks the fit, then rejects unknown labels with a clear list, then looks up each label in the dict.- The first assert is a round trip: decoding the codes gives back the original 5,000 labels.
Alternative: scikit-learn’s sklearn.preprocessing.LabelEncoder has the same interface and also sorts the classes. Use it in real projects (module 33). For features, as opposed to a target, prefer OneHotEncoder, because integer codes suggest an order (basic < premium < standard) that does not exist.
M18-C11 · Fix the bug: the property that calls itself
Section titled “M18-C11 · Fix the bug: the property that calls itself”Fix the bug: a ResampleRule sets the bucket size, in minutes, for resampling the 10-minute readings of data/sensors.csv. A bucket must be a positive multiple of 10. Creating a rule crashes with RecursionError: maximum recursion depth exceeded. Fix the class, then show one valid rule and one rejected value.
60 6 {'_minutes': 60}rejected: minutes must be a positive multiple of 10, got 25class ResampleRule: def __init__(self, minutes: int): self.minutes = minutes
@property def minutes(self) -> int: return self.minutes
@minutes.setter def minutes(self, value: int) -> None: if value <= 0 or value % 10 != 0: raise ValueError(f"minutes must be a positive multiple of 10, got {value}") self.minutes = value
@property def readings_per_bucket(self) -> int: return self.minutes // 10
hourly = ResampleRule(60)print(hourly.minutes, hourly.readings_per_bucket)# TODO: fix the property so that the rule works, then try ResampleRule(25)Hint 1
Follow self.minutes = value inside the setter. Which method does that line call?
Hint 2
The getter has the same problem as the setter. Both must use another attribute name for the stored value.
Solution
class ResampleRule: def __init__(self, minutes: int): self.minutes = minutes # runs the setter: correct
@property def minutes(self) -> int: return self._minutes
@minutes.setter def minutes(self, value: int) -> None: if value <= 0 or value % 10 != 0: raise ValueError(f"minutes must be a positive multiple of 10, got {value}") self._minutes = value
@property def readings_per_bucket(self) -> int: return self.minutes // 10
hourly = ResampleRule(60)print(hourly.minutes, hourly.readings_per_bucket, vars(hourly))try: ResampleRule(25)except ValueError as exc: print("rejected:", exc)
assert ResampleRule(1440).readings_per_bucket == 144assert vars(hourly) == {"_minutes": 60}60 6 {'_minutes': 60}rejected: minutes must be a positive multiple of 10, got 25How it works:
- In the bug,
self.minutes = valueinside the setter assigns to the property again, so the setter calls itself without end. Python stops it withRecursionErrorafter about 1,000 calls. - The getter had the same loop:
return self.minutescalls the getter. - The fix stores the value as
self._minutes. That is a plain instance attribute, not the property, so there is no loop. self.minutes = minutesin__init__must stay as it is: it is the line that runs the validation for new objects.
Alternative: if the bucket size never changes after creation, validate it once in __init__ and store it as a plain attribute, or use a frozen dataclass (module 21). A property is worth it when later assignments must be checked too.
M18-C12 · A vocabulary for review texts
Section titled “M18-C12 · A vocabulary for review texts”Text models turn words into integer ids with a vocabulary: a mapping from each known word (token) to an id. Write a class Vocabulary. A static method tokenize(text) lowercases the text and keeps runs of letters with re.findall(r"[a-z]+", ...). A class method from_texts(texts, min_count=2) counts the tokens and keeps those that appear at least min_count times, sorted alphabetically, with ids from 1; id 0 is reserved for unknown words. Add a property size (known words plus 1) and a method encode(text). Build it from the first 200 review texts of data/reviews.csv. Print the vocabulary size, the tokens of "LOVE IT!!! Easy to use.", the ids of that text and the ids of "Zebra-striped quantum toaster".
vocabulary size: 264['love', 'it', 'easy', 'to', 'use'][127, 114, 66, 234, 242][0, 0, 0, 0]import csvimport refrom collections import Counter
class Vocabulary: unknown_id = 0
def __init__(self, tokens: list[str]): # TODO: map each token to an id from 1 ...
# TODO: static method tokenize, class method from_texts, property size, encode
with open("data/reviews.csv", newline="", encoding="utf-8") as f: texts = [row["text"] for _, row in zip(range(200), csv.DictReader(f))]# TODO: build the vocabulary (min_count=2) and print "vocabulary size: ..."# TODO: print the tokens and the ids of "LOVE IT!!! Easy to use."# TODO: print the ids of "Zebra-striped quantum toaster"Hint 1
Counter() counts the tokens; counter.update(tokens) adds the tokens of one text. Keep [t for t, n in counter.items() if n >= min_count] and sort it.
Hint 2
In __init__, build self._ids = {token: i for i, token in enumerate(tokens, start=1)}. encode uses self._ids.get(token, self.unknown_id).
Solution
import csvimport refrom collections import Counterfrom typing import Self
class Vocabulary: unknown_id = 0 # id for every word that is not in the vocabulary
def __init__(self, tokens: list[str]): self._ids = {token: i for i, token in enumerate(tokens, start=1)}
@staticmethod def tokenize(text: str) -> list[str]: return re.findall(r"[a-z]+", text.lower())
@classmethod def from_texts(cls, texts: list[str], min_count: int = 2) -> Self: counts: Counter[str] = Counter() for text in texts: counts.update(cls.tokenize(text)) kept = sorted(token for token, n in counts.items() if n >= min_count) return cls(kept)
@property def size(self) -> int: return len(self._ids) + 1 # + 1 for the unknown id
def encode(self, text: str) -> list[int]: return [self._ids.get(t, self.unknown_id) for t in self.tokenize(text)]
with open("data/reviews.csv", newline="", encoding="utf-8") as f: texts = [row["text"] for _, row in zip(range(200), csv.DictReader(f))]
vocab = Vocabulary.from_texts(texts, min_count=2)print("vocabulary size:", vocab.size)print(Vocabulary.tokenize("LOVE IT!!! Easy to use."))print(vocab.encode("LOVE IT!!! Easy to use."))print(vocab.encode("Zebra-striped quantum toaster"))
assert vocab.encode("") == []assert Vocabulary.from_texts(["a b", "a"], min_count=2).size == 2vocabulary size: 264['love', 'it', 'easy', 'to', 'use'][127, 114, 66, 234, 242][0, 0, 0, 0]How it works:
tokenizeneeds no vocabulary, so it is static. The class method andencodeboth call it, so the two always split text the same way.from_textsdoes the counting and filtering, then callscls(kept).__init__only builds the lookup dict from a clean token list, which makes it easy to test.- Words seen fewer than
min_counttimes are dropped. Rare words add many ids and teach a model little. encodemaps unknown words to 0, so the made-up product words all become 0.
Alternative: scikit-learn’s CountVectorizer (module 41) builds a vocabulary with min_df and a token pattern, and turns texts into count vectors. The idea is the same; the class above shows what happens inside.
Challenge
Section titled “Challenge”M18-X01 · Streaming anomaly detection per sensor
Section titled “M18-X01 · Streaming anomaly detection per sensor”A monitoring service reads data/sensors.csv row by row, in time order, and must flag temperature anomalies: values far from the usual values of their own sensor. Build it from two classes.
RunningStats: the Welford running mean and population standard deviation of the lesson, withupdate(value)and read-only propertiescount,meanandstd.ZScoreDetector: keeps oneRunningStatsper sensor in a dict. Its z-score of a value is|value - mean| / std, the distance from the mean in standard deviations. Validated properties:threshold(a number > 0) andwarmup(anint≥ 2, the number of readings a sensor needs before it can flag anything). A methodcheck(sensor_id, timestamp, value)returnsTrueand records the anomaly when the sensor is warmed up and the z-score is above the threshold. Otherwise it updates the statistics. Anomalies are not added to the statistics, so a spike cannot distort the mean.
Run it with threshold=4.0 and warmup=144 (one day). Skip blank temperatures. Print the count per sensor, the total and the largest anomaly.
S1: 8 anomaliesS2: 11 anomaliesS3: 10 anomaliesS4: 8 anomaliestotal: 37largest: ('S4', '2024-05-03T16:00:00', 44.36, 11.6)rejected: warmup must be >= 2, got 1import csvimport math
class RunningStats: # TODO: Welford update, count, mean, std (population) ...
class ZScoreDetector: def __init__(self, threshold: float = 4.0, warmup: int = 144): self.threshold = threshold self.warmup = warmup # TODO: a dict of RunningStats per sensor and a list of anomalies
# TODO: validated properties threshold and warmup # TODO: check(sensor_id, timestamp, value) -> bool
# TODO: feed every non-blank temperature to the detector# TODO: print the anomalies per sensor, the total and the largest oneHint 1
Get or create the statistics of a sensor with self._stats.setdefault(sensor_id, RunningStats()). Store each anomaly as a tuple (sensor_id, timestamp, value, z).
Hint 2
In check, compute the z-score only when stats.count >= self.warmup and stats.std > 0. If it is above the threshold, record it and return True without calling update. The largest anomaly is max(anomalies, key=lambda a: a[3]).
Solution
import csvimport mathfrom collections import Counter
class RunningStats: """Running mean and population standard deviation (Welford)."""
def __init__(self): self._count = 0 self._mean = 0.0 self._m2 = 0.0
def update(self, value: float) -> None: self._count += 1 delta = value - self._mean self._mean += delta / self._count self._m2 += delta * (value - self._mean)
@property def count(self) -> int: return self._count
@property def mean(self) -> float: return self._mean
@property def std(self) -> float: return math.sqrt(self._m2 / self._count) if self._count else 0.0
class ZScoreDetector: def __init__(self, threshold: float = 4.0, warmup: int = 144): self.threshold = threshold self.warmup = warmup self._stats: dict[str, RunningStats] = {} self.anomalies: list[tuple[str, str, float, float]] = []
@property def threshold(self) -> float: return self._threshold
@threshold.setter def threshold(self, value: float) -> None: if isinstance(value, bool) or not isinstance(value, (int, float)): raise TypeError(f"threshold must be a number, got {value!r}") if value <= 0: raise ValueError(f"threshold must be > 0, got {value}") self._threshold = value
@property def warmup(self) -> int: return self._warmup
@warmup.setter def warmup(self, value: int) -> None: if isinstance(value, bool) or not isinstance(value, int): raise TypeError(f"warmup must be an int, got {value!r}") if value < 2: raise ValueError(f"warmup must be >= 2, got {value}") self._warmup = value
def check(self, sensor_id: str, timestamp: str, value: float) -> bool: stats = self._stats.setdefault(sensor_id, RunningStats()) if stats.count >= self.warmup and stats.std > 0: z = abs(value - stats.mean) / stats.std if z > self.threshold: self.anomalies.append((sensor_id, timestamp, value, round(z, 1))) return True # do not let the spike distort the statistics stats.update(value) return False
detector = ZScoreDetector(threshold=4.0, warmup=144)with open("data/sensors.csv", newline="", encoding="utf-8") as f: for row in csv.DictReader(f): text = row["temperature_c"] if text: # skip blank cells detector.check(row["sensor_id"], row["timestamp"], float(text))
per_sensor = Counter(a[0] for a in detector.anomalies)for sensor_id in sorted(per_sensor): print(f"{sensor_id}: {per_sensor[sensor_id]} anomalies")print("total:", len(detector.anomalies))print("largest:", max(detector.anomalies, key=lambda a: a[3]))try: detector.warmup = 1except ValueError as exc: print("rejected:", exc)
assert all(a[3] > 4.0 for a in detector.anomalies)assert detector.warmup == 144assert len({a[0] for a in detector.anomalies}) == 4S1: 8 anomaliesS2: 11 anomaliesS3: 10 anomaliesS4: 8 anomaliestotal: 37largest: ('S4', '2024-05-03T16:00:00', 44.36, 11.6)rejected: warmup must be >= 2, got 1How it works:
- Composition: an object that holds other objects and delegates work to them. The detector does not compute statistics itself. It owns one
RunningStatsobject per sensor and asks it forcount,meanandstd. Each class has one job. - Per-sensor state:
setdefaultcreates the statistics of a sensor on its first reading. S4 runs warmer than S1, so one shared mean would flag normal S4 readings. - Warm-up: with fewer than 144 readings, the mean and the standard deviation are not reliable, so the detector only learns.
- No contamination: an anomaly is recorded but not added to the statistics. One spike of +15 °C would otherwise raise the mean and the standard deviation and hide the next spike.
- Validation: the setters protect the two settings for the whole life of the detector, as the rejected
warmup = 1shows.
Alternative: pandas (module 25) computes a rolling mean and standard deviation per sensor with groupby("sensor_id")["temperature_c"].rolling(144). That is faster for a file on disk. The streaming class wins when readings arrive one at a time from a live feed and you cannot keep them all.
M18-X02 · Refactor a churn rule into a model class
Section titled “M18-X02 · Refactor a churn rule into a model class”Refactor: turn the churn analysis in the starter into a model class with the scikit-learn interface. GroupRateModel learns the churn rate of each group of customers, where a group is the pair (contract, tenure_months <= 6).
fit(rows)learnsrates_(a dict from group to churn rate) andbase_rate_(the overall rate, used for a group not seen in training). It returnsself.predict_proba(rows)returns the learned rate of each row’s group.predict(rows)returns 1 when that rate is at leastthreshold, else 0.__init__(threshold=0.5)storesthresholdunchanged, under the same name: this is the scikit-learn rule for estimators (see the lesson’s Example 5). A private method_validate_params()checks it at the start offitandpredict: a wrong type raisesTypeError, a number outside 0 to 1 raisesValueError.- Both predict methods raise
NotFittedErrorbeforefit.
Split data/customers.csv deterministically: every fifth row (index 0, 5, 10…) is the test set, the rest is the training set. Print the learned rates, then the accuracy and the recall (the share of real churners that the model flags) on the test set for the thresholds 0.5 and 0.3. Then set threshold = 1.5 and show the error that predict raises. Explain the result in a comment.
month-to-month new=False churn rate 0.201month-to-month new=True churn rate 0.469one-year new=False churn rate 0.085one-year new=True churn rate 0.167two-year new=False churn rate 0.030two-year new=True churn rate 0.069base rate 0.194threshold 0.5: flagged 0, accuracy 0.813, recall 0.000threshold 0.3: flagged 208, accuracy 0.799, recall 0.519ValueError: threshold must be in [0, 1], got 1.5import csv
with open("data/customers.csv", newline="", encoding="utf-8") as f: rows = list(csv.DictReader(f))
# Procedural version: churn rate per group, on all rowscounts = {}for row in rows: group = (row["contract"], int(row["tenure_months"]) <= 6) n, churned = counts.get(group, (0, 0)) counts[group] = (n + 1, churned + int(row["churned"]))for group, (n, churned) in sorted(counts.items()): print(group, round(churned / n, 3))
# TODO: a NotFittedError class and a GroupRateModel class# TODO: split into train (index % 5 != 0) and test (index % 5 == 0)# TODO: fit on train; print rates_; print accuracy and recall for thresholds 0.5 and 0.3# TODO: set model.threshold = 1.5 and print the ValueError that predict raisesHint 1
Write a static method _group(row) that returns the pair. Both fit and predict_proba call it, so the grouping rule lives in one place.
Hint 2
Accuracy is the share of predictions equal to the truth. Recall is (rows with prediction 1 and truth 1) / (rows with truth 1). Change the threshold on the fitted model with model.threshold = 0.3; you do not need to fit again.
Hint 3
At threshold 0.5, look at the largest learned rate. Can any group reach 0.5? What does the model predict for every customer then?
Solution
import csvfrom typing import Self
class NotFittedError(ValueError): """Raised when a model is used before fit()."""
class GroupRateModel: """Predict churn from the training churn rate of (contract, is_new) groups."""
def __init__(self, threshold: float = 0.5): self.threshold = threshold # stored unchanged; checked in fit and predict
def _validate_params(self) -> None: value = self.threshold if isinstance(value, bool) or not isinstance(value, (int, float)): raise TypeError(f"threshold must be a number, got {value!r}") if not 0 <= value <= 1: raise ValueError(f"threshold must be in [0, 1], got {value}")
@staticmethod def _group(row: dict[str, str]) -> tuple[str, bool]: return row["contract"], int(row["tenure_months"]) <= 6
def fit(self, rows: list[dict[str, str]]) -> Self: self._validate_params() counts: dict[tuple[str, bool], list[int]] = {} for row in rows: counts.setdefault(self._group(row), []).append(int(row["churned"])) self.rates_ = {g: sum(v) / len(v) for g, v in sorted(counts.items())} self.base_rate_ = sum(int(r["churned"]) for r in rows) / len(rows) return self
def predict_proba(self, rows: list[dict[str, str]]) -> list[float]: if not hasattr(self, "rates_"): raise NotFittedError("GroupRateModel is not fitted yet; call fit() first") return [self.rates_.get(self._group(r), self.base_rate_) for r in rows]
def predict(self, rows: list[dict[str, str]]) -> list[int]: self._validate_params() return [int(p >= self.threshold) for p in self.predict_proba(rows)]
with open("data/customers.csv", newline="", encoding="utf-8") as f: rows = list(csv.DictReader(f))train = [row for i, row in enumerate(rows) if i % 5 != 0]test = [row for i, row in enumerate(rows) if i % 5 == 0]y_test = [int(row["churned"]) for row in test]
model = GroupRateModel().fit(train)for (contract, is_new), rate in model.rates_.items(): print(f"{contract:<15} new={is_new!s:<5} churn rate {rate:.3f}")print(f"base rate {model.base_rate_:.3f}")
for threshold in (0.5, 0.3): model.threshold = threshold pred = model.predict(test) accuracy = sum(p == t for p, t in zip(pred, y_test)) / len(y_test) recall = sum(p and t for p, t in zip(pred, y_test)) / sum(y_test) print(f"threshold {threshold}: flagged {sum(pred):>3}, " f"accuracy {accuracy:.3f}, recall {recall:.3f}")
model.threshold = 1.5 # accepted here, like a scikit-learn parametertry: model.predict(test)except ValueError as exc: print("ValueError:", exc)
# At 0.5 no group reaches the threshold, so the model predicts "no churn" for# everyone: accuracy equals the share of loyal customers and recall is 0.# At 0.3 the model flags new month-to-month customers. Accuracy drops a little,# but the model now finds about half of the churners. Accuracy alone misleads# on imbalanced classes.assert max(model.rates_.values()) < 0.5assert len(train) == 4000 and len(test) == 1000month-to-month new=False churn rate 0.201month-to-month new=True churn rate 0.469one-year new=False churn rate 0.085one-year new=True churn rate 0.167two-year new=False churn rate 0.030two-year new=True churn rate 0.069base rate 0.194threshold 0.5: flagged 0, accuracy 0.813, recall 0.000threshold 0.3: flagged 208, accuracy 0.799, recall 0.519ValueError: threshold must be in [0, 1], got 1.5How it works:
- State moved into the object: the counts of the procedural version become the learned attributes
rates_andbase_rate_, set only byfit. The fitted check ishasattr(self, "rates_"). - One grouping rule: the static method
_groupis used by bothfitandpredict_proba, so training and prediction can never group rows differently. - Hyperparameter vs learned attribute:
thresholdis a setting of the model.__init__stores it unchanged, and_validate_params()checks it where it is used, as scikit-learn does. Somodel.threshold = 1.5is accepted, and the error comes atpredict. Changing the threshold does not require a new fit, because the rates do not depend on it. - Train/test split: the model learns on 4,000 customers and is judged on 1,000 others, so the scores are not inflated by memorized rows.
- The result: the highest group rate is about 0.47 (new month-to-month customers), below 0.5. So threshold 0.5 flags nobody. Its accuracy equals the share of loyal customers, the score of the trivial “nobody churns” rule. Threshold 0.3 trades a little accuracy for real recall. Module 36 chooses thresholds properly with precision, recall and cost.
Alternative: add more columns to the group, such as logins_last_30d <= 3, and fall back to base_rate_ for small groups. Better still, use logistic regression (module 36), which combines many features without splitting the data into ever smaller groups.
M18-X03 · Parse HTTP requests into objects
Section titled “M18-X03 · Parse HTTP requests into objects”Outside data science, every web framework turns the raw text of an HTTP request into an object. Build a small HttpRequest class.
__init__(method, path, query, headers, body)stores clean values.methodis a validated property: one ofGET,POST,PUT,PATCH,DELETE, stored in upper case.- A class method
from_raw(raw)parses the request text: the request line (METHOD target HTTP/1.1), the header lines up to the first empty line, and the body after it. Lines end with\r\n. The target"/api/products?page=2&per_page=10"splits into the path and a query dict of strings. - Header names are case-insensitive: store them in lower case, and add a method
header(name, default=None). - Properties:
is_json(theContent-Typestarts withapplication/json) andjson(the parsed body, orNonewhen the request is not JSON).
Parse the two requests in the starter and print what an API endpoint would read from them.
GET /api/products {'page': '2', 'per_page': '10'}page: 2 | request id: 7f3ais JSON: False | body: NonePOST /api/predict application/json; charset=utf-8C03991 6 2rejected: unsupported HTTP method 'FETCH'import json
get_raw = ( "GET /api/products?page=2&per_page=10 HTTP/1.1\r\n" "Host: shop.example.com\r\n" "Accept: application/json\r\n" "X-Request-ID: 7f3a\r\n" "\r\n")post_raw = ( "post /api/predict HTTP/1.1\r\n" "Host: ml.example.com\r\n" "Content-Type: application/json; charset=utf-8\r\n" "\r\n" '{"customer_id": "C03991", "tenure_months": 6, "logins_last_30d": 2}')
class HttpRequest: # TODO: __init__, the method property, from_raw, header, is_json, json ...
# TODO: parse both requests and print their method, path, query, a header and the JSON# TODO: show that HttpRequest("FETCH", "/", {}, {}, "") is rejectedHint 1
raw.split("\r\n\r\n", 1) separates the head from the body. head.split("\r\n") gives the request line first, then one header per line.
Hint 2
target.partition("?") gives the path, the "?" and the query text. Each key=value pair of the query text splits with pair.split("=", 1). A header line splits with line.split(":", 1); strip the spaces.
Hint 3
json is a property that returns json.loads(self.body) if self.is_json else None. Inside the class, the module json and the property json do not clash, because the property is reached only through self.json.
Solution
import jsonfrom typing import Self
get_raw = ( "GET /api/products?page=2&per_page=10 HTTP/1.1\r\n" "Host: shop.example.com\r\n" "Accept: application/json\r\n" "X-Request-ID: 7f3a\r\n" "\r\n")post_raw = ( "post /api/predict HTTP/1.1\r\n" "Host: ml.example.com\r\n" "Content-Type: application/json; charset=utf-8\r\n" "\r\n" '{"customer_id": "C03991", "tenure_months": 6, "logins_last_30d": 2}')
class HttpRequest: allowed_methods = ("GET", "POST", "PUT", "PATCH", "DELETE")
def __init__( self, method: str, path: str, query: dict[str, str], headers: dict[str, str], body: str, ): self.method = method # validated by the property self.path = path self.query = query self._headers = {name.lower(): value for name, value in headers.items()} self.body = body
@property def method(self) -> str: return self._method
@method.setter def method(self, value: str) -> None: if value.upper() not in self.allowed_methods: raise ValueError(f"unsupported HTTP method {value!r}") self._method = value.upper()
@staticmethod def _parse_query(text: str) -> dict[str, str]: pairs = (item.split("=", 1) for item in text.split("&") if item) return {key: value for key, value in pairs}
@classmethod def from_raw(cls, raw: str) -> Self: head, _, body = raw.partition("\r\n\r\n") request_line, *header_lines = head.split("\r\n") method, target, _version = request_line.split(" ") path, _, query_text = target.partition("?") headers = {} for line in header_lines: name, value = line.split(":", 1) headers[name.strip()] = value.strip() return cls(method, path, cls._parse_query(query_text), headers, body)
def header(self, name: str, default: str | None = None) -> str | None: return self._headers.get(name.lower(), default)
@property def is_json(self) -> bool: return self.header("content-type", "").startswith("application/json")
@property def json(self) -> dict | None: return json.loads(self.body) if self.is_json else None
get_req = HttpRequest.from_raw(get_raw)print(get_req.method, get_req.path, get_req.query)page = int(get_req.query.get("page", "1"))print("page:", page, "| request id:", get_req.header("x-request-id"))print("is JSON:", get_req.is_json, "| body:", get_req.json)
post_req = HttpRequest.from_raw(post_raw)print(post_req.method, post_req.path, post_req.header("CONTENT-TYPE"))features = post_req.jsonprint(features["customer_id"], features["tenure_months"], features["logins_last_30d"])
try: HttpRequest("FETCH", "/", {}, {}, "")except ValueError as exc: print("rejected:", exc)
assert get_req.query == {"page": "2", "per_page": "10"}assert post_req.method == "POST" and post_req.is_jsonassert get_req.header("Missing", "none") == "none"GET /api/products {'page': '2', 'per_page': '10'}page: 2 | request id: 7f3ais JSON: False | body: NonePOST /api/predict application/json; charset=utf-8C03991 6 2rejected: unsupported HTTP method 'FETCH'How it works:
from_rawdoes the parsing and__init__takes clean values. A test can build a request directly, as the rejectedFETCHcall does, without writing raw text.partition("\r\n\r\n")cuts the text at the first empty line: before it is the head, after it the body.request_line, *header_lines = ...is star-unpacking (module 04).- Header names are stored in lower case, and
header()lowercases the name it looks up. SoCONTENT-TYPE,Content-Typeandcontent-typefind the same value, as HTTP requires. - The
methodproperty normalizesposttoPOSTand rejects unknown methods, at creation and on every later assignment. jsonreads like data but is computed frombody. An endpoint of a prediction API reads the customer features from it; module 44 does this with FastAPI.
Alternative: the standard library parses the query string with urllib.parse.parse_qs("page=2&per_page=10"). It returns lists ({'page': ['2'], ...}), because a key can repeat in a URL. Real frameworks (Starlette, Flask, Django) use their own request classes with the same ideas: properties, case-insensitive headers and lazy body parsing.
M18-X04 · Early stopping for a training loop
Section titled “M18-X04 · Early stopping for a training loop”Training loops often stop when the validation loss (the error on data the model does not train on) stops improving. Write an EarlyStopping class, as PyTorch and Keras users write them.
- Validated properties:
patience(anint≥ 1: how many epochs without improvement are allowed) andmin_delta(a number ≥ 0: the smallest drop that counts as an improvement). A wrong type raisesTypeError; a value out of range raisesValueError. step(val_loss) -> boolis called once per epoch. It counts epochs from 1. When the loss is lower thanbest_loss_ - min_delta, it stores the newbest_loss_andbest_epoch_and resets an internal counter. Otherwise it increases the counter. It returnsTruewhen the counter reachespatience.- A property
stopped_epochreturns the epoch at whichstepfirst returnedTrue, orNone. reset()clears the state, so the object can watch a second run.
Run it on the two validation-loss logs in the starter, with patience=3, min_delta=0.005. Then run log A again with patience=5 on the same object after reset().
patience=3: stop at epoch 7, best epoch 4 (loss 0.581)patience=3: no early stop, best epoch 10 (loss 0.52)patience=5: no early stop, best epoch 9 (loss 0.574)rejected: patience must be an int >= 1, got 0log_a = [0.92, 0.71, 0.60, 0.581, 0.578, 0.576, 0.590, 0.602, 0.574, 0.571, 0.640]log_b = [1.10, 0.95, 0.83, 0.74, 0.67, 0.62, 0.58, 0.55, 0.53, 0.52]
class EarlyStopping: def __init__(self, patience: int = 3, min_delta: float = 0.0): self.patience = patience self.min_delta = min_delta self.reset()
# TODO: validated properties patience and min_delta # TODO: reset(), step(val_loss) -> bool and the property stopped_epoch
def run(stopper: EarlyStopping, losses: list[float]) -> None: # TODO: call step() for each loss and stop the loop when it returns True # TODO: print the stop epoch (or "no early stop"), the best epoch and the best loss ...Hint 1
reset() sets self.best_loss_ = math.inf, self.best_epoch_ = 0, self._epoch = 0, self._bad_epochs = 0 and self._stopped_epoch = None. math.inf is larger than every loss, so the first loss is always an improvement.
Hint 2
For log A with min_delta=0.005: 0.578 is not lower than 0.581 − 0.005 = 0.576. So epoch 5 does not count as an improvement, although the loss went down.
Solution
import math
log_a = [0.92, 0.71, 0.60, 0.581, 0.578, 0.576, 0.590, 0.602, 0.574, 0.571, 0.640]log_b = [1.10, 0.95, 0.83, 0.74, 0.67, 0.62, 0.58, 0.55, 0.53, 0.52]
class EarlyStopping: def __init__(self, patience: int = 3, min_delta: float = 0.0): self.patience = patience self.min_delta = min_delta self.reset()
@property def patience(self) -> int: return self._patience
@patience.setter def patience(self, value: int) -> None: if isinstance(value, bool) or not isinstance(value, int): raise TypeError(f"patience must be an int, got {type(value).__name__}") if value < 1: raise ValueError(f"patience must be an int >= 1, got {value!r}") self._patience = value
@property def min_delta(self) -> float: return self._min_delta
@min_delta.setter def min_delta(self, value: float) -> None: if isinstance(value, bool) or not isinstance(value, (int, float)): raise TypeError(f"min_delta must be a number, got {type(value).__name__}") if value < 0: raise ValueError(f"min_delta must be a number >= 0, got {value!r}") self._min_delta = value
def reset(self) -> None: self.best_loss_ = math.inf self.best_epoch_ = 0 self._epoch = 0 self._bad_epochs = 0 self._stopped_epoch: int | None = None
def step(self, val_loss: float) -> bool: self._epoch += 1 if val_loss < self.best_loss_ - self.min_delta: self.best_loss_ = val_loss self.best_epoch_ = self._epoch self._bad_epochs = 0 else: self._bad_epochs += 1 if self._bad_epochs >= self.patience and self._stopped_epoch is None: self._stopped_epoch = self._epoch return self._stopped_epoch is not None
@property def stopped_epoch(self) -> int | None: return self._stopped_epoch
def run(stopper: EarlyStopping, losses: list[float]) -> None: for loss in losses: if stopper.step(loss): break stop = stopper.stopped_epoch when = f"stop at epoch {stop}" if stop else "no early stop" print(f"patience={stopper.patience}: {when}, " f"best epoch {stopper.best_epoch_} (loss {stopper.best_loss_})")
stopper = EarlyStopping(patience=3, min_delta=0.005)run(stopper, log_a)stopper.reset()run(stopper, log_b)stopper.reset()stopper.patience = 5run(stopper, log_a)try: stopper.patience = 0except ValueError as exc: print("rejected:", exc)
assert stopper.patience == 5check = EarlyStopping(patience=3, min_delta=0.005)assert [check.step(x) for x in log_a[:7]] == [False] * 6 + [True]patience=3: stop at epoch 7, best epoch 4 (loss 0.581)patience=3: no early stop, best epoch 10 (loss 0.52)patience=5: no early stop, best epoch 9 (loss 0.574)rejected: patience must be an int >= 1, got 0How it works:
- Log A, patience 3: the best loss is 0.581 at epoch 4. Epochs 5, 6 and 7 are not better by at least 0.005, so the counter reaches 3 at epoch 7 and training stops.
- Log B: the loss keeps dropping by more than 0.005, so the counter never reaches 3. The best epoch is the last one.
- Log A, patience 5: after
reset(), the same object watches a new run. Epoch 9 (0.574) beats 0.581 by 0.007, so the counter restarts. Epoch 10 (0.571) is lower, but by less than 0.005, so it does not count. The log ends before the counter reaches 5, so there is no early stop, and the best epoch is 9. More patience found a better model than the stop at epoch 7. - Encapsulation: the epoch and bad-epoch counters are internal (
_epoch,_bad_epochs), the results that callers read end with_, and the settings are validated properties. A training loop needs onlystep(). - The last assert replays the first 7 epochs and checks the exact sequence of decisions.
Alternative: PyTorch Lightning and Keras ship an EarlyStopping callback with the same settings (patience, min_delta). Most also restore the weights of the best epoch, which you would store in step() next to best_loss_ (module 42).
M18-X05 · Fix the bugs: a model registry
Section titled “M18-X05 · Fix the bugs: a model registry”Fix the bugs: a small registry lets a script create models by name, a pattern you build fully in module 22. The code has five bugs. One class attribute looks suspicious but is correct: find it and explain in a comment why it must stay shared. The data are the first 8 house prices of data/houses.csv, in thousands of USD. When the script works, add one more call: ModelRegistry.create("knn"), and print the KeyError it raises for this unknown name.
[540.0, 540.0, 540.0]learned mean: 560.0models created: 1KeyError: "unknown model 'knn'; known: ['mean']"class ModelRegistry: _factories = {} # name -> class
def register(cls, name, factory): if name in cls._factories: raise ValueError(f"model {name!r} is already registered") cls._factories[name] = factory
@classmethod def create(cls, name, **params): if name not in cls._factories: raise KeyError(f"unknown model {name!r}; known: {sorted(cls._factories)}") return cls._factories[name](**params)
class MeanRegressor: created = 0
def __init__(self, shift=0.0): self.shift = shift # stored unchanged, scikit-learn style self.created += 1
def fit(self, y): self.__mean = sum(y) / len(y)
@staticmethod def predict(self, n): return [round(self.__mean + self.shift, 1)] * n
ModelRegistry.register("mean", MeanRegressor)prices = [1097.5, 486.5, 223.0, 431.0, 1080.0, 327.5, 455.0, 379.5]model = ModelRegistry.create("mean", shift=-20.0).fit(prices)print(model.predict(3))print("learned mean:", round(model.__mean, 1))print("models created:", MeanRegressor.created)# TODO: fix the five bugs; keep the correct class attribute and explain why# TODO: then call ModelRegistry.create("knn") and print "KeyError:" and the errorHint 1
Fix one error at a time: run, read the last traceback line, fix, run again. The first error appears at the line ModelRegistry.register("mean", MeanRegressor).
Hint 2
Look for: two wrong or missing decorators, a counter that never counts, a method that must return self, and a name that Python renames inside the class.
Hint 3
A registry must be the same for the whole program. If _factories were created per instance, which instance would hold the registered models? The registry is never instantiated at all.
Solution
from typing import Self
class ModelRegistry: # Correct as a class attribute: the registry is shared on purpose. Every # caller must see the same name -> class mapping, and nobody creates # ModelRegistry instances; all methods are class methods. _factories: dict[str, type] = {}
@classmethod # bug 1: without it, "mean" was passed as cls def register(cls, name: str, factory: type) -> None: if name in cls._factories: raise ValueError(f"model {name!r} is already registered") cls._factories[name] = factory
@classmethod def create(cls, name: str, **params): if name not in cls._factories: raise KeyError(f"unknown model {name!r}; known: {sorted(cls._factories)}") return cls._factories[name](**params)
class MeanRegressor: created = 0
def __init__(self, shift: float = 0.0): self.shift = shift # stored unchanged, scikit-learn style MeanRegressor.created += 1 # bug 2: self.created += 1 never counted
def fit(self, y: list[float]) -> Self: self.mean_ = sum(y) / len(y) # bug 5: a public learned attribute, not __mean return self # bug 4: fit must return self
def predict(self, n: int) -> list[float]: # bug 3: no @staticmethod return [round(self.mean_ + self.shift, 1)] * n
ModelRegistry.register("mean", MeanRegressor)prices = [1097.5, 486.5, 223.0, 431.0, 1080.0, 327.5, 455.0, 379.5]model = ModelRegistry.create("mean", shift=-20.0).fit(prices)print(model.predict(3))print("learned mean:", round(model.mean_, 1))print("models created:", MeanRegressor.created)try: ModelRegistry.create("knn")except KeyError as exc: print("KeyError:", exc)
assert isinstance(model, MeanRegressor) and model.shift == -20.0assert MeanRegressor.created == 1assert "_factories" not in vars(MeanRegressor)[540.0, 540.0, 540.0]learned mean: 560.0models created: 1KeyError: "unknown model 'knn'; known: ['mean']"How it works:
- Bug 1, the missing
@classmethod:ModelRegistry.register("mean", MeanRegressor)called a plain function withcls="mean"andname=MeanRegressor, and nofactory. The run failed withTypeError: ModelRegistry.register() missing 1 required positional argument: 'factory'. - Bug 4,
fitreturnedNone: so.fit(prices)gaveNone, andmodel.predict(3)raisedAttributeError: 'NoneType' object has no attribute 'predict'.fitmust end withreturn self. (This error comes second when you fix the bugs in the order they appear.) - Bug 3, the wrong
@staticmethod: a static method receives no instance, somodel.predict(3)passed 3 asselfand nothing asn:TypeError: MeanRegressor.predict() missing 1 required positional argument: 'n'.predictreads the state of the model, so it is an instance method. - Bug 5, the mangled name: inside the class,
self.__meanwas renamed toself._MeanRegressor__mean. Outside the class,model.__meanis not renamed, so it raisedAttributeError: 'MeanRegressor' object has no attribute '__mean'. The fix stores the scikit-learn style learned attributemean_, which is public on purpose. - Bug 2, the counter: this bug raises nothing; the script just prints
models created: 0.self.created += 1created an instance attribute, and the class counter stayed at 0.MeanRegressor.created += 1changes the shared value. - The correct class attribute:
_factoriesis shared state by design. A mutable class attribute is a bug only when each instance needs its own copy.
Alternative: a module-level dict FACTORIES = {} and two functions register() and create() do the same job without a class. Module 22 turns the registry into a decorator: @register("mean") above the class definition.