20. The Python data model
len(df), df["price"], a @ b, model(x) and with torch.no_grad(): look like built-in syntax. They are ordinary methods with special names. In this module you write those methods yourself. The minilearn estimators get a readable repr, a Dataset behaves like a list, a Vector supports +, -, *, abs() and @, and a Money type adds up revenue with sum().
What you will learn
Section titled “What you will learn”- Explain how Python turns syntax such as
len(x),x[0],a + bandprint(x)into calls of special methods. - Write
__repr__and__str__, and choose between them with the f-string flags!rand!s. - Define equality and hashing with
__eq__and__hash__, and explain why defining__eq__makes a class unhashable. - Define an order with
__lt__andfunctools.total_ordering, sosorted(),min()andmax()work. - Build containers with
__len__,__getitem__(indexes, slices and names),__iter__,__contains__and__bool__. - Write callable objects (
__call__), context managers (__enter__,__exit__) and arithmetic operators, including reflected operators andNotImplemented.
Prerequisites
Section titled “Prerequisites”- 18. Classes and objects:
class,__init__,self, methods,@classmethod,@property, and the firstminilearnclasses. - 19. Inheritance and polymorphism:
BaseEstimatorwithget_paramsandset_params, the mixins,isinstance()and duck typing. - 10. Iterators and generators: the iteration protocol,
__iter__,__next__and generators. - 11. Decorators and context managers: the
withstatement and the context manager protocol. - 04. Data structures: hashable values, sets and dict keys.
Concepts
Section titled “Concepts”The data model: syntax calls special methods
Section titled “The data model: syntax calls special methods”Python’s data model is the set of rules that connects the language to your objects. It says which method runs when you write len(x), x[0], a + b, for item in x or print(x). The methods have names with two leading and two trailing underscores, such as __len__. Module 10 called them dunder methods and module 11 called them special methods: both names mean the same thing. You rarely call them yourself. Python calls them for you.
| You write | Python calls | Typical use |
|---|---|---|
repr(m), the REPL echo |
m.__repr__() |
KNNClassifier(n_neighbors=5) |
print(m), str(m), f"{m}" |
m.__str__() |
21.7 °C |
a == b |
a.__eq__(b) |
compare two configurations |
hash(a), {a}, d[a] |
a.__hash__() |
set members, dict keys |
a < b, sorted(items) |
a.__lt__(b) |
rank model scores |
len(ds) |
ds.__len__() |
number of samples |
ds[0], ds[10:20], ds["sqft"] |
ds.__getitem__(key) |
rows, slices, columns |
for row in ds |
ds.__iter__() |
loop over samples |
x in ds |
ds.__contains__(x) |
membership test |
if ds: |
ds.__bool__() |
truth value |
model(X) |
model.__call__(X) |
a model used like a function |
with t: |
t.__enter__(), t.__exit__(...) |
set up and clean up |
a + b, a @ b, abs(a) |
a.__add__(b), a.__matmul__(b), a.__abs__() |
vector math |
Giving an operator such as + a meaning for your own class is called operator overloading. This is how the data science libraries feel native. df["price"] calls DataFrame.__getitem__. a @ b on two NumPy arrays calls ndarray.__matmul__. model(x) on a PyTorch network calls nn.Module.__call__, which runs your forward() method.
Python looks up a special method on the class of the object, not on the object itself. len(log) runs type(log).__len__(log). An attribute that you attach to one instance does not change the syntax:
class SensorLog: """The temperature readings of one sensor, in °C."""
def __init__(self, sensor_id: str, values: list[float]) -> None: self.sensor_id = sensor_id self.values = values
def __len__(self) -> int: return len(self.values)
log = SensorLog("S1", [19.5, 20.7, 20.1, 21.2, 21.2, 20.8])print(len(log))log.__len__ = lambda: 99 # an instance attribute, not a class methodprint(len(log), log.__len__())66 99len(log) still gives 6, because Python asks the class SensorLog. Only the explicit call log.__len__() finds the instance attribute. The readings are lines 37 to 42 of data/readings.txt, the same values as the module 01 project.
flowchart LR
A["len(log)"] --> B["type(log) is SensorLog"]
B --> C["SensorLog.__len__(log)"]
C --> D{"int ≥ 0?"}
D -- yes --> E["6"]
D -- no --> F["TypeError or ValueError"]
len() also checks the result. __len__ must return an int that is 0 or more. A negative value raises ValueError: __len__() should return >= 0.
__repr__ and __str__: two ways to show an object
Section titled “__repr__ and __str__: two ways to show an object”A class without these methods shows only its type and its memory address, for example <__main__.Reading object at 0x10a3f2b50>. The address changes on every run and tells you nothing about the data:
class Reading: """One temperature reading from one sensor."""
def __init__(self, sensor_id: str, celsius: float) -> None: self.sensor_id = sensor_id self.celsius = celsius
text = repr(Reading("S1", 21.7))print(text.split(" at ")[0])print("object at 0x" in text)<__main__.Reading objectTrue(The code cuts the text before the address, because the address differs on your machine.) Python gives every object two text forms:
__repr__returns the developer representation: an unambiguous text for debugging, logs and the REPL. When it is practical, it looks like the code that rebuilds the object, such asReading('S1', 21.7).__str__returns the user representation: a readable text for reports and end users, such asS1: 21.7 °C.
class Reading: """One temperature reading from one sensor."""
def __init__(self, sensor_id: str, celsius: float) -> None: self.sensor_id = sensor_id self.celsius = celsius
def __repr__(self) -> str: return f"Reading({self.sensor_id!r}, {self.celsius!r})"
def __str__(self) -> str: return f"{self.sensor_id}: {self.celsius:.1f} °C"
r = Reading("S1", 21.7)print(r) # print() calls str()print(repr(r))print([r, Reading("S2", 19.25)]) # a list shows the repr of each itemprint(f"{r} | {r!r} | {r=}")S1: 21.7 °CReading('S1', 21.7)[Reading('S1', 21.7), Reading('S2', 19.25)]S1: 21.7 °C | Reading('S1', 21.7) | r=Reading('S1', 21.7)An f-string can choose the form with a conversion flag, written after the expression: !r calls repr(), !s calls str() and !a calls ascii(). The debug form {r=} uses the repr too. Inside __repr__, {self.sensor_id!r} adds the quotes, so 'S1' is visibly a string and not a variable name.
| Code | Uses | Falls back to |
|---|---|---|
print(x), str(x), f"{x}", f"{x!s}" |
__str__ |
__repr__ when the class has no __str__ |
repr(x), REPL echo, f"{x!r}", f"{x=}" |
__repr__ |
object.__repr__ (type and address) |
| items inside a list, dict, set or tuple | __repr__ of each item |
|
f"{x:.2f}", format(x, ".2f") |
__format__ |
object.__format__, which rejects a non-empty spec |
The rule: always write __repr__. Write __str__ only when users need a friendlier text than the repr. If you write only one, write __repr__, because str() falls back to it and nothing falls back to __str__.
Equality and hashing: __eq__ and __hash__
Section titled “Equality and hashing: __eq__ and __hash__”By default, a == b compares identity: it is True only when a and b are the same object, as with a is b. Two readings with the same data are still two objects:
print(Reading("S1", 21.7) == Reading("S1", 21.7))FalseA gateway that sends a reading twice creates exactly this situation. To compare by value, write __eq__. Return the special value NotImplemented when the other object is not of a type you know. Python then asks the other object, and if it also declines, falls back to identity (False for ==). You get != for free: Python inverts the result of __eq__.
class Reading: """One temperature reading from one sensor."""
def __init__(self, sensor_id: str, celsius: float) -> None: self.sensor_id = sensor_id self.celsius = celsius
def __repr__(self) -> str: return f"Reading({self.sensor_id!r}, {self.celsius!r})"
def __eq__(self, other: object) -> bool: if not isinstance(other, Reading): return NotImplemented return (self.sensor_id, self.celsius) == (other.sensor_id, other.celsius)
a, b = Reading("S1", 21.7), Reading("S1", 21.7)print(a == b, a != b, a is b)print(a == "S1: 21.7", a in [Reading("S2", 19.25), b])print(Reading.__hash__)True False FalseFalse TrueNonein on a list uses ==, so a in [...] finds b. The last line is the surprise: Reading.__hash__ is None. When a class defines __eq__ and no __hash__, Python sets __hash__ to None. The instances are now unhashable: they cannot go into a set or be a dict key.
unique = {a, b}TypeError: unhashable type: 'Reading'Python does this to protect the hash contract: if a == b, then hash(a) == hash(b) must be true. A set first uses the hash to find a bucket, then == to check the items in that bucket (module 04 explains hash tables). The default hash comes from the identity, so two equal readings would land in different buckets, and the set would keep both. An unhashable class is safer than a broken one.
To make the class hashable again, write __hash__ from the same fields as __eq__. Hashing a tuple of the fields is the standard way:
class Reading: """One temperature reading from one sensor."""
def __init__(self, sensor_id: str, celsius: float) -> None: self.sensor_id = sensor_id self.celsius = celsius
def __repr__(self) -> str: return f"Reading({self.sensor_id!r}, {self.celsius!r})"
def __eq__(self, other: object) -> bool: if not isinstance(other, Reading): return NotImplemented return (self.sensor_id, self.celsius) == (other.sensor_id, other.celsius)
def __hash__(self) -> int: return hash((self.sensor_id, self.celsius))
batch = [Reading("S1", 21.7), Reading("S2", 19.25), Reading("S1", 21.7)]unique = set(batch)print(len(batch), len(unique))print(hash(batch[0]) == hash(batch[2]))last_seen = {Reading("S1", 21.7): "2024-05-01T00:10:00"}print(last_seen[batch[2]])3 2True2024-05-01T00:10:00The duplicate disappears from the set, and an equal reading finds the dict entry. Do not print hash values themselves: the hash of a string changes between runs (Python randomizes it for security), so only compare hashes.
Hash only objects that do not change. If you change a field after the object went into a set, its hash changes, and the set looks in the wrong bucket: x in s becomes False for an object that is in s. A class whose objects never change after creation is immutable, like str and tuple. A small immutable class that is defined by its values, such as a reading, a money amount or a vector, is a value object. The value objects on this page are immutable by convention: their attributes are public, but no code assigns to them after __init__. Exercise M20-C07 makes the fields truly read-only with @property, and module 21’s @dataclass(frozen=True) enforces it for you. Value objects are the classes that should define __eq__ and __hash__. Objects that change, such as a model that learns in fit(), should define at most __eq__ and stay unhashable.
Ordering: __lt__ and functools.total_ordering
Section titled “Ordering: __lt__ and functools.total_ordering”sorted(), min(), max(), list.sort() and heapq compare items with <. Without an order, they fail. Here is a Money class that stores an amount as whole cents, the exact format that module 01 recommended for money. Money(94995) is 949.95 USD:
class Money: """An exact amount of money, stored as whole cents."""
def __init__(self, cents: int, currency: str = "USD") -> None: self.cents = cents # an int: exact, no float rounding self.currency = currency
def __repr__(self) -> str: return f"Money({self.cents!r}, {self.currency!r})"
order_totals = [Money(94995), Money(1499), Money(24900)]print(sorted(order_totals))TypeError: '<' not supported between instances of 'Money' and 'Money'The six comparison operators each have a rich comparison method: __lt__ (<), __le__ (<=), __gt__ (>), __ge__ (>=), __eq__ (==) and __ne__ (!=). Writing all six is tedious and easy to get wrong. The class decorator functools.total_ordering writes the missing ones for you. You write __eq__ and one of __lt__, __le__, __gt__ or __ge__:
from functools import total_ordering
@total_orderingclass Money: """An exact amount of money, stored as whole cents."""
def __init__(self, cents: int, currency: str = "USD") -> None: self.cents = cents # an int: exact, no float rounding self.currency = currency
def __repr__(self) -> str: return f"Money({self.cents!r}, {self.currency!r})"
def __str__(self) -> str: return f"{self.cents / 100:,.2f} {self.currency}"
def _check(self, other: "Money") -> None: if self.currency != other.currency: raise ValueError(f"cannot compare {self.currency} with {other.currency}")
def __eq__(self, other: object) -> bool: if not isinstance(other, Money): return NotImplemented return (self.cents, self.currency) == (other.cents, other.currency)
def __hash__(self) -> int: return hash((self.cents, self.currency))
def __lt__(self, other: object) -> bool: if not isinstance(other, Money): return NotImplemented self._check(other) return self.cents < other.cents
order_totals = [Money(94995), Money(1499), Money(24900), Money(1349)]print(sorted(order_totals))print(min(order_totals), "|", max(order_totals))print(Money(1499) >= Money(1349), Money(1499) <= Money(1499))[Money(1349, 'USD'), Money(1499, 'USD'), Money(24900, 'USD'), Money(94995, 'USD')]13.49 USD | 949.95 USDTrue TrueThe four amounts are the revenue of the first four lines of store S01 in data/sales.csv. @total_ordering built >= from __lt__ and __eq__. Comparing USD with EUR raises a ValueError with a clear message, because no exchange rate is known. Comparing with a non-Money value returns NotImplemented, and Python raises the usual TypeError.
Give a class an order only when it has one natural order. Money has one. A Reading does not: you might sort by temperature, by sensor or by time. For those classes, pass a key function (module 05) instead: sorted(readings, key=lambda r: r.celsius). The order must also agree with __eq__: if neither a < b nor b < a, then a == b should be True.
Containers: __len__, __getitem__, __iter__ and __contains__
Section titled “Containers: __len__, __getitem__, __iter__ and __contains__”A container is an object that holds other objects: a list, a dict, a DataFrame, a dataset. Four methods make your class a container:
| Method | Syntax | Must |
|---|---|---|
__len__(self) |
len(x) |
return an int ≥ 0 |
__getitem__(self, key) |
x[key] |
return the item; raise IndexError (positions) or KeyError (names) when it is missing |
__iter__(self) |
for item in x, list(x), sum(x) |
return a new iterator; a generator method is easiest |
__contains__(self, item) |
item in x |
return a bool |
x[2:4] passes a slice object to __getitem__. A slice object holds the start, stop and step of the slice. The usual way to support slices is to pass the key on to a list, which understands both integers and slices:
from collections.abc import Iteratorfrom typing import Self
class SensorLog: """The temperature readings of one sensor, in °C."""
def __init__(self, sensor_id: str, values: list[float]) -> None: self.sensor_id = sensor_id self.values = values
def __repr__(self) -> str: return f"SensorLog({self.sensor_id!r}, {self.values!r})"
def __len__(self) -> int: return len(self.values)
def __getitem__(self, key: int | slice) -> float | Self: if isinstance(key, slice): return type(self)(self.sensor_id, self.values[key]) return self.values[key]
def __iter__(self) -> Iterator[float]: yield from self.values
log = SensorLog("S1", [19.5, 20.7, 20.1, 21.2, 21.2, 20.8])print(len(log), log[0], log[-1])print(log[1:3], log[::2])print(sum(log) / len(log), max(log), sorted(log)[:2])6 19.5 20.8SensorLog('S1', [20.7, 20.1]) SensorLog('S1', [19.5, 20.1, 21.2])20.583333333333332 21.2 [19.5, 20.1]A slice returns a new SensorLog, not a plain list, just as a slice of a list is a list and a slice of a DataFrame is a DataFrame. type(self)(...) builds an object of the same class, so a subclass keeps its type. sum(), max() and sorted() work because they only need __iter__.
Python has fallbacks when a method is missing:
| Missing | Python uses instead |
|---|---|
__iter__ |
__getitem__(0), __getitem__(1), … until IndexError (the old sequence protocol) |
__contains__ |
a loop over __iter__ (or the __getitem__ fallback), comparing with == |
__bool__ |
__len__: an empty container is falsy |
__ne__ |
the inverse of __eq__ |
__radd__, __rmul__, … |
nothing: the operation raises TypeError |
The fallback for in is a linear scan. Write __contains__ when a faster or a different test exists. A valid range is a container with infinitely many members, so it cannot loop at all. It can still answer in:
class Interval: """A closed range of valid values, such as a sensor's data-sheet range."""
def __init__(self, low: float, high: float) -> None: self.low = low self.high = high
def __repr__(self) -> str: return f"Interval({self.low!r}, {self.high!r})"
def __contains__(self, value: object) -> bool: return isinstance(value, int | float) and self.low <= value <= self.high
valid = Interval(19.0, 23.0)print(21.7 in valid, 18.4 in valid, "21.7" in valid)print([v for v in log if v not in valid])True False False[]not in calls the same method and inverts the result. All six readings of the log lie inside the valid range from the sensor’s data sheet.
For a full read-only sequence, inherit from collections.abc.Sequence. You write __getitem__ and __len__, and the abstract base class (module 19) adds __contains__, __iter__, __reversed__, index() and count() for you. collections.abc.Mapping does the same for dict-like classes.
Callable objects: __call__
Section titled “Callable objects: __call__”A callable is anything you can call with parentheses: a function, a class, a method, or an object whose class defines __call__. A callable object is a function that carries its settings and its state in attributes. Here, Clip caps outliers, a step called winsorizing:
class Clip: """Limit values to [low, high]: a callable data-cleaning step."""
def __init__(self, low: float, high: float) -> None: self.low = low self.high = high self.n_clipped = 0 # state: how many values were changed
def __repr__(self) -> str: return f"Clip({self.low!r}, {self.high!r})"
def __call__(self, value: float) -> float: clipped = min(max(value, self.low), self.high) if clipped != value: self.n_clipped += 1 return clipped
clip = Clip(19.0, 23.0)raw = [21.7, 18.2, 22.9, 31.5, 20.1] # 31.5 is a sensor glitchprint(list(map(clip, raw)))print(clip, "changed", clip.n_clipped, "values")print(callable(clip), callable(log), callable(len))[21.7, 19.0, 22.9, 23.0, 20.1]Clip(19.0, 23.0) changed 2 valuesTrue False Truemap() accepts clip exactly like a function, because map() only needs a callable. A closure (module 05) can do the same job. A callable object wins when you want a readable repr, several settings you can inspect, or state such as n_clipped. scikit-learn scorers, PyTorch layers, torchvision transforms and functools.partial objects are all callable objects.
Context managers: __enter__ and __exit__
Section titled “Context managers: __enter__ and __exit__”Module 11 introduced the context manager protocol. In data model terms, with x as name: calls type(x).__enter__(x) before the block and type(x).__exit__(x, exc_type, exc_value, traceback) after it, even when the block raises.
__exit__ returns |
Effect |
|---|---|
None or False (the usual case) |
an exception from the block continues after cleanup |
True |
the exception is suppressed, and the program goes on after the with block |
Two patterns fit model code very well. A timer measures a training step. A temporary setting changes a model’s parameters for one block and always restores them. Example 6 builds the second one.
Arithmetic operators and NotImplemented
Section titled “Arithmetic operators and NotImplemented”Each arithmetic operator has a method:
| Operator | Method | Reflected | In place |
|---|---|---|---|
a + b |
__add__ |
__radd__ |
__iadd__ (+=) |
a - b |
__sub__ |
__rsub__ |
__isub__ |
a * b |
__mul__ |
__rmul__ |
__imul__ |
a / b |
__truediv__ |
__rtruediv__ |
__itruediv__ |
a // b, a % b |
__floordiv__, __mod__ |
__rfloordiv__, __rmod__ |
__ifloordiv__, __imod__ |
a ** b |
__pow__ |
__rpow__ |
__ipow__ |
a @ b |
__matmul__ |
__rmatmul__ |
__imatmul__ |
-a, +a, abs(a) |
__neg__, __pos__, __abs__ |
For a + b, Python first calls a.__add__(b). If that method is missing or returns NotImplemented, Python calls the reflected method of the right operand, b.__radd__(a). If that also fails, Python raises TypeError. NotImplemented is a special value (not an exception) that means “I do not know how to do this; ask the other operand”. Do not confuse it with the exception NotImplementedError from module 06.
sequenceDiagram
participant P as Python
participant A as left operand (0)
participant B as right operand (Money)
P->>A: int.__add__(0, money)
A-->>P: NotImplemented
P->>B: Money.__radd__(money, 0)
B-->>P: Money(1349, 'USD')
The diagram shows why sum() needs __radd__. sum(items) starts from the integer 0 and computes 0 + first_item. int does not know Money, so Python asks Money.__radd__. Here is Money with arithmetic:
from decimal import Decimal
@total_orderingclass Money: """An exact amount of money, stored as whole cents."""
def __init__(self, cents: int, currency: str = "USD") -> None: self.cents = cents # an int: exact, no float rounding self.currency = currency
@classmethod def parse(cls, text: str, currency: str = "USD") -> "Money": """Money.parse("13.49") -> Money(1349): Decimal reads the text exactly.""" return cls(int(Decimal(text) * 100), currency)
def __repr__(self) -> str: return f"Money({self.cents!r}, {self.currency!r})"
def __str__(self) -> str: return f"{self.cents / 100:,.2f} {self.currency}"
def __eq__(self, other: object) -> bool: if not isinstance(other, Money): return NotImplemented return (self.cents, self.currency) == (other.cents, other.currency)
def __hash__(self) -> int: return hash((self.cents, self.currency))
def __lt__(self, other: object) -> bool: if not isinstance(other, Money): return NotImplemented self._check(other) return self.cents < other.cents
def _check(self, other: "Money") -> None: if self.currency != other.currency: raise ValueError(f"cannot combine {self.currency} with {other.currency}")
def __add__(self, other: object) -> "Money": if not isinstance(other, Money): return NotImplemented self._check(other) return Money(self.cents + other.cents, self.currency)
def __radd__(self, other: object) -> "Money": if other == 0: # sum() starts from 0 return self return NotImplemented
def __mul__(self, factor: object) -> "Money": if not isinstance(factor, int | float): return NotImplemented return Money(round(self.cents * factor), self.currency)
__rmul__ = __mul__ # 3 * price is the same as price * 3
def __bool__(self) -> bool: return self.cents != 0
unit_price = Money.parse("189.99")lines = [5 * unit_price, Money(1499), Money(24900), Money(1499) * 0.9]print(lines)print(sum(lines))print(Money.parse("100.00") + Money.parse("0.10") + Money.parse("0.20"))[Money(94995, 'USD'), Money(1499, 'USD'), Money(24900, 'USD'), Money(1349, 'USD')]1,227.43 USD100.30 USDThe four lines are the same order lines as before: 5 camping tents, one pack of socks, headphones and a pack of socks with a 10% discount. Money.parse() is an alternative constructor (module 18) that reads a price text such as "189.99" with decimal.Decimal, which converts the text exactly, without a float in between. 5 * unit_price works through __rmul__, and __rmul__ = __mul__ reuses the same function because multiplication by a number does not depend on the order. sum(lines) works through __radd__. Whole cents keep the result exact: 0.10 + 0.20 is exactly 0.30 here, unlike with floats.
A type that the methods do not accept gives a clear TypeError, because every method returned NotImplemented:
print(Money(1499) + 5)TypeError: unsupported operand type(s) for +: 'Money' and 'int'Adding a plain number to money is ambiguous (5 dollars? 5 cents?), so Money refuses it. Never raise TypeError yourself inside __add__ for an unknown type: return NotImplemented, so the other operand gets its chance.
+= calls __iadd__ if the class has it, otherwise a = a + b. Immutable value objects (Money, Vector, int, str) do not define __iadd__, so total += line builds a new object and rebinds the name. Mutable containers such as list define __iadd__ and change the object in place.
Truth value: __bool__
Section titled “Truth value: __bool__”if x: and while x: call bool(x). Python tries __bool__ first, then __len__ (an empty container is falsy), and otherwise treats the object as truthy. Money above defines __bool__, so a zero amount is falsy, like the number 0:
refund = Money(0)print(bool(refund), bool(Money(1349)))print(bool(log), bool(log[6:]), bool(clip))False TrueTrue False Truelog[6:] is an empty SensorLog, so __len__ makes it falsy. Clip has neither __bool__ nor __len__, so every Clip is truthy. __bool__ must return a real bool. Use it only when “false” has an obvious meaning: zero, empty or nothing. A pandas DataFrame raises ValueError: The truth value of a DataFrame is ambiguous instead, because “true” could mean “not empty” or “all values true”.
Which methods to write
Section titled “Which methods to write”“Behave like a built-in” means: the same syntax does the same kind of thing for your class as for list, dict, int or str. A reader then understands your class without reading its code. Implement only what the class really is.
| Your class is… | Write | Example |
|---|---|---|
| any class | __repr__ |
every minilearn class |
| a value (amount, vector, score) | __eq__, __hash__; __lt__ with @total_ordering if it has a natural order |
Money, Vector, ModelScore |
| a mutable object with a configuration | __repr__, maybe __eq__, no __hash__ |
estimators |
| a collection of items | __len__, __getitem__, __iter__; __contains__ if a faster test exists |
Dataset, Pipeline |
| something with one main action | __call__ |
a scorer, a cleaning step, a model |
| a resource or a temporary change | __enter__, __exit__ |
a timer, temporary params |
| a mathematical object | arithmetic methods and their reflected forms | Vector, Money |
Do not overload an operator with a surprising meaning. pipeline + model that trains the model would confuse every reader. A named method such as fit() is clearer.
Worked examples
Section titled “Worked examples”The examples continue minilearn, the small scikit-learn-like library of Part 3. They need the metric functions, NotFittedError, check_is_fitted() and the mixins from module 19, copied unchanged. Open the block to see them, and paste it at the top of your script.
minilearn so far: metrics, NotFittedError, check_is_fitted and the mixins
import csvimport inspectimport mathimport statisticsfrom collections import Counterfrom collections.abc import Iteratorfrom functools import total_orderingfrom typing import Any, Self
# --- metrics.py (modules 18 and 19) ---------------------------------------def _check_lengths(y_true: list[float], y_pred: list[float]) -> None: if len(y_true) != len(y_pred): raise ValueError(f"lengths differ: {len(y_true)} vs {len(y_pred)}") if not y_true: raise ValueError("y_true is empty")
def mean_squared_error(y_true: list[float], y_pred: list[float]) -> float: """Mean of the squared differences between the truth and the predictions.""" _check_lengths(y_true, y_pred) return sum((t - p) ** 2 for t, p in zip(y_true, y_pred, strict=True)) / len(y_true)
def r2_score(y_true: list[float], y_pred: list[float]) -> float: """1 - SS_res / SS_tot: the share of the variance of y that the model explains.""" _check_lengths(y_true, y_pred) mean = sum(y_true) / len(y_true) ss_res = sum((t - p) ** 2 for t, p in zip(y_true, y_pred, strict=True)) ss_tot = sum((t - mean) ** 2 for t in y_true) if ss_tot == 0: # constant y_true: scikit-learn returns 1.0 or 0.0 here return 1.0 if ss_res == 0 else 0.0 return 1 - ss_res / ss_tot
def accuracy_score(y_true: list[Any], y_pred: list[Any]) -> float: """Share of predictions that equal the true label.""" _check_lengths(y_true, y_pred) return sum(t == p for t, p in zip(y_true, y_pred, strict=True)) / len(y_true)
# --- base.py (module 19) ------------------------------------------------class NotFittedError(ValueError, AttributeError): """Raised when a model or transformer is used before fit()."""
def check_is_fitted(estimator: object) -> None: """Raise NotFittedError if the object has no learned attribute (name ending _).""" learned = [k for k in vars(estimator) if k.endswith("_") and not k.startswith("__")] if not learned: name = type(estimator).__name__ raise NotFittedError(f"{name} is not fitted yet; call fit() first")
class TransformerMixin: """fit_transform() for every transformer."""
def fit_transform(self, X: list[list[float]], y: Any = None) -> list[list[float]]: return self.fit(X, y).transform(X)
class RegressorMixin: """score() as R² for every regressor."""
def score(self, X: list[list[float]], y: list[float]) -> float: return r2_score(y, self.predict(X))
class ClassifierMixin: """score() as accuracy for every classifier."""
def score(self, X: list[list[float]], y: list[Any]) -> float: return accuracy_score(y, self.predict(X))Example 1 — Print and compare estimators like scikit-learn
Section titled “Example 1 — Print and compare estimators like scikit-learn”Goal: In a notebook or a log, print(model) should show KNNClassifier(n_neighbors=15), not a memory address. Tests should be able to ask “do these two models have the same configuration?”.
Step 1 — Add __repr__ and __eq__ to BaseEstimator
Section titled “Step 1 — Add __repr__ and __eq__ to BaseEstimator”class BaseEstimator: """get_params() and set_params() for every estimator."""
@classmethod def _get_param_names(cls) -> list[str]: params = inspect.signature(cls.__init__).parameters.values() return [ p.name for p in params if p.name != "self" and p.kind not in (p.VAR_POSITIONAL, p.VAR_KEYWORD) ]
def get_params(self) -> dict[str, Any]: return {name: getattr(self, name) for name in self._get_param_names()}
def set_params(self, **params: Any) -> Self: valid = self._get_param_names() for name, value in params.items(): if name not in valid: raise ValueError( f"Invalid parameter {name!r} for {type(self).__name__}. " f"Valid: {valid}" ) setattr(self, name, value) return self
def __repr__(self) -> str: args = ", ".join(f"{k}={v!r}" for k, v in self.get_params().items()) return f"{type(self).__name__}({args})"
def __eq__(self, other: object) -> bool: if not isinstance(other, BaseEstimator): return NotImplemented same_type = type(self) is type(other) return same_type and self.get_params() == other.get_params()The first part is module 19’s BaseEstimator, unchanged. The highlighted lines are new. __repr__ builds the constructor call from the parameters, so it works for every subclass without extra code. type(self).__name__ gives the name of the subclass, not BaseEstimator. __eq__ says that two estimators are equal when they have the same class and the same parameters.
Step 2 — Build the estimators on the new base
Section titled “Step 2 — Build the estimators on the new base”StandardScaler, LinearRegression and KNNClassifier are module 19’s classes, copied unchanged, including the checks at the start of each fit(). DummyRegressor is new: a baseline model that always predicts the mean or the median of the training targets. With strategy="mean", it does the same as module 19’s MeanRegressor. Any real model must beat it.
StandardScaler, LinearRegression and KNNClassifier (module 19), and DummyRegressor (new)
class StandardScaler(TransformerMixin, BaseEstimator): """Standardize features: z = (x - mean_) / scale_, column by column."""
def __init__(self, with_mean: bool = True, with_std: bool = True) -> None: self.with_mean = with_mean self.with_std = with_std
def fit(self, X: list[list[float]], y: Any = None) -> Self: if not X: raise ValueError("cannot fit on an empty X") n = len(X) columns = list(zip(*X, strict=True)) means = [sum(col) / n for col in columns] stds = [ self._population_std(col, mean) for col, mean in zip(columns, means, strict=True) ] self.mean_ = means if self.with_mean else [0.0] * len(columns) self.scale_ = stds if self.with_std else [1.0] * len(columns) self.n_features_in_ = len(columns) return self
def transform(self, X: list[list[float]]) -> list[list[float]]: self._check(X) params = list(zip(self.mean_, self.scale_, strict=True)) return [ [(v - m) / s for v, (m, s) in zip(row, params, strict=True)] for row in X ]
def inverse_transform(self, Z: list[list[float]]) -> list[list[float]]: self._check(Z) params = list(zip(self.mean_, self.scale_, strict=True)) return [[z * s + m for z, (m, s) in zip(row, params, strict=True)] for row in Z]
@staticmethod def _population_std(values: tuple[float, ...], mean: float) -> float: variance = sum((v - mean) ** 2 for v in values) / len(values) std = variance**0.5 return std if std > 0 else 1.0 # a constant column stays unchanged
def _check(self, X: list[list[float]]) -> None: check_is_fitted(self) for row in X: if len(row) != self.n_features_in_: raise ValueError( f"X has {len(row)} features, but the scaler was fitted " f"with {self.n_features_in_}" )
class LinearRegression(RegressorMixin, BaseEstimator): """Fit y = coef_ * x + intercept_ for a single feature x."""
def __init__(self, fit_intercept: bool = True) -> None: self.fit_intercept = fit_intercept
@staticmethod def _single_column(X: list[list[float]]) -> list[float]: for row in X: if len(row) != 1: raise ValueError( f"LinearRegression supports exactly 1 feature, got {len(row)}" ) return [row[0] for row in X]
def fit(self, X: list[list[float]], y: list[float]) -> Self: x = self._single_column(X) if len(x) != len(y) or len(x) < 2: raise ValueError("X and y need the same length, with at least 2 samples") if self.fit_intercept: x_mean = sum(x) / len(x) y_mean = sum(y) / len(y) else: x_mean = y_mean = 0.0 sxx = sum((xi - x_mean) ** 2 for xi in x) sxy = sum((xi - x_mean) * (yi - y_mean) for xi, yi in zip(x, y, strict=True)) if sxx == 0: raise ValueError("cannot fit a line: all x values are equal") self.coef_ = sxy / sxx self.intercept_ = y_mean - self.coef_ * x_mean return self
def predict(self, X: list[list[float]]) -> list[float]: check_is_fitted(self) return [self.coef_ * x + self.intercept_ for x in self._single_column(X)]
class KNNClassifier(ClassifierMixin, BaseEstimator): """Majority vote of the k nearest training rows (Euclidean distance)."""
def __init__(self, n_neighbors: int = 5) -> None: self.n_neighbors = n_neighbors
def fit(self, X: list[list[float]], y: list[Any]) -> Self: if self.n_neighbors < 1: raise ValueError(f"n_neighbors must be >= 1, got {self.n_neighbors}") self.X_train_ = [list(row) for row in X] self.y_train_ = list(y) self.classes_ = sorted(set(y)) return self
def _predict_one(self, row: list[float]) -> Any: def distance(i: int) -> tuple[float, int]: return math.dist(row, self.X_train_[i]), i # equal distances: lower index
nearest = sorted(range(len(self.X_train_)), key=distance) votes = Counter(self.y_train_[i] for i in nearest[: self.n_neighbors]) return max(self.classes_, key=lambda label: votes[label]) # ties: smaller
def predict(self, X: list[list[float]]) -> list[Any]: check_is_fitted(self) return [self._predict_one(row) for row in X]
class DummyRegressor(RegressorMixin, BaseEstimator): """Baseline: always predict the mean or the median of the training y."""
def __init__(self, strategy: str = "mean") -> None: self.strategy = strategy
def fit(self, X: list[list[float]], y: list[float]) -> Self: if self.strategy not in ("mean", "median"): raise ValueError(f"unknown strategy {self.strategy!r}") if self.strategy == "mean": self.constant_ = statistics.fmean(y) else: self.constant_ = statistics.median(y) return self
def predict(self, X: list[list[float]]) -> list[float]: check_is_fitted(self) return [self.constant_ for _ in X]models = [ StandardScaler(), LinearRegression(fit_intercept=False), KNNClassifier(n_neighbors=15), DummyRegressor(strategy="median"),]for model in models: print(model)print(models[2:])StandardScaler(with_mean=True, with_std=True)LinearRegression(fit_intercept=False)KNNClassifier(n_neighbors=15)DummyRegressor(strategy='median')[KNNClassifier(n_neighbors=15), DummyRegressor(strategy='median')]No subclass defines __repr__. Each one inherits it from BaseEstimator, and get_params() finds the right parameter names for each class. print() uses the repr, because no class defines __str__. A list shows the repr of each item.
Step 3 — See why !r matters
Section titled “Step 3 — See why !r matters”params = DummyRegressor(strategy="median").get_params()print(", ".join(f"{k}={v}" for k, v in params.items()))print(", ".join(f"{k}={v!r}" for k, v in params.items()))rebuilt = eval(repr(models[2]))print(rebuilt, rebuilt == models[2], rebuilt is models[2])strategy=medianstrategy='median'KNNClassifier(n_neighbors=15) True FalseWithout !r, the string parameter loses its quotes, and strategy=median looks like a variable. With !r, the repr is valid Python. eval() runs the text as code and builds an equal, separate model. Use eval() only on text you wrote yourself, never on input from users or files.
Step 4 — Compare configurations with ==
Section titled “Step 4 — Compare configurations with ==”a = KNNClassifier(n_neighbors=5)b = KNNClassifier(5)print(a == b, a != b, a is b)print(a == KNNClassifier(3), a == LinearRegression(), a == "KNNClassifier(5)")print(KNNClassifier(15) in models, models.index(LinearRegression(fit_intercept=False)))True False FalseFalse False FalseTrue 1a and b are two objects with the same configuration, so they are equal but not identical. A string is not an estimator: __eq__ returns NotImplemented, str also declines, and Python falls back to identity, which gives False. in and list.index() use ==, so they find a new object with equal parameters.
Step 5 — Try to put estimators in a set
Section titled “Step 5 — Try to put estimators in a set”print(BaseEstimator.__hash__)grid = {KNNClassifier(5), KNNClassifier(15), KNNClassifier(5)}NoneTypeError: unhashable type: 'KNNClassifier'BaseEstimator defines __eq__ and no __hash__, so Python set its __hash__ to None, and every subclass inherits that. This is the right result here. An estimator changes: set_params() changes its parameters and fit() adds learned attributes. A hash built from the parameters would change too, and the estimator would get lost inside a set.
Step 6 — Skip duplicate configurations with a hashable key
Section titled “Step 6 — Skip duplicate configurations with a hashable key”def config_key(model: BaseEstimator) -> tuple[str, tuple[tuple[str, Any], ...]]: """A hashable snapshot of the model's class and parameters.""" return type(model).__name__, tuple(sorted(model.get_params().items()))
candidates = [KNNClassifier(5), KNNClassifier(15), KNNClassifier(5), LinearRegression()]seen = set()for model in candidates: key = config_key(model) if key in seen: print("skip ", model) continue seen.add(key) print("train ", model)print(config_key(candidates[1]))train KNNClassifier(n_neighbors=5)train KNNClassifier(n_neighbors=15)skip KNNClassifier(n_neighbors=5)train LinearRegression(fit_intercept=True)('KNNClassifier', (('n_neighbors', 15),))The key is a tuple of strings and numbers, so it is hashable and it never changes. A search over a grid of hyperparameters can use such keys to skip a configuration that it already trained, or to cache its scores in a dict.
Common mistakes:
- Writing
f"{k}={v}"in__repr__. String parameters lose their quotes, and the repr is no longer valid code. Use!r. - Hard-coding the class name:
return f"BaseEstimator({args})". Every model then prints asBaseEstimator. Usetype(self).__name__. - Adding
__hash__from the parameters to a mutable class. The object moves to another bucket when a parameter changes. Keep estimators unhashable and build a key when you need one. - Raising
TypeErrorin__eq__for an unknown type.model == "text"would then crash. ReturnNotImplemented.
Example 2 — Use a Dataset like a list
Section titled “Example 2 — Use a Dataset like a list”Goal: The Dataset class from module 18 holds X and y for data/houses.csv. Give it len(), indexing, slicing, column access by name and a for loop, so it behaves like a list of samples and a little like a DataFrame.
Step 1 — Write the container methods
Section titled “Step 1 — Write the container methods”class Dataset: """Features X (one row per sample) and a target y (one value per sample)."""
def __init__(self, X: list[list[float]], y: list[float], feature_names: list[str]): if not X: raise ValueError("a Dataset needs at least one sample") if len(X) != len(y): raise ValueError(f"X has {len(X)} rows but y has {len(y)} values") width = len(feature_names) for i, row in enumerate(X): if len(row) != width: raise ValueError(f"row {i} has {len(row)} values, expected {width}") self.X = X self.y = y self.feature_names = list(feature_names)
@property def n_samples(self) -> int: return len(self.X)
@property def n_features(self) -> int: return len(self.feature_names)
@staticmethod def _parse(text: str, column: str, line: int) -> float | None: """Return the number in a CSV cell, or None for a blank cell.""" if not text.strip(): return None try: return float(text) except ValueError: message = f"line {line}: {column!r} is not a number: {text!r}" raise ValueError(message) from None
@classmethod def from_csv( cls, path: str, target: str, features: list[str], skip_missing: bool = False ) -> Self: """Load the given feature columns and the target column of a CSV file.
A row with a blank cell in one of these columns raises ValueError, or is skipped when skip_missing is True. """ X: list[list[float]] = [] y: list[float] = [] with open(path, newline="", encoding="utf-8") as f: reader = csv.DictReader(f) header = reader.fieldnames or [] missing = [name for name in [*features, target] if name not in header] if missing: raise ValueError(f"{path}: unknown columns {missing}") for line, row in enumerate(reader, start=2): # line 1 is the header values = [cls._parse(row[name], name, line) for name in features] label = cls._parse(row[target], target, line) numbers = [v for v in values if v is not None] if label is None or len(numbers) < len(values): if skip_missing: continue raise ValueError(f"line {line}: blank value; use skip_missing=True") X.append(numbers) y.append(label) return cls(X, y, features)
def column(self, name: str) -> list[float]: """Return the values of one feature.""" index = self.feature_names.index(name) return [row[index] for row in self.X]
def split_at(self, n_first: int) -> tuple[Self, Self]: """Split into the first n_first samples and the rest, keeping the order.""" if not 0 < n_first < self.n_samples: raise ValueError(f"n_first must be between 1 and {self.n_samples - 1}") cls = type(self) first = cls(self.X[:n_first], self.y[:n_first], self.feature_names) rest = cls(self.X[n_first:], self.y[n_first:], self.feature_names) return first, rest
def __repr__(self) -> str: return f"Dataset(n_samples={len(self)}, features={self.feature_names!r})"
def __len__(self) -> int: return len(self.X)
def __getitem__(self, key: int | slice | str) -> Any: if isinstance(key, int): # one sample: (features, target) return self.X[key], self.y[key] if isinstance(key, slice): # a smaller Dataset return type(self)(self.X[key], self.y[key], self.feature_names) if isinstance(key, str): # one feature column, by name if key not in self.feature_names: raise KeyError(key) return self.column(key) kind = type(key).__name__ raise TypeError(f"Dataset indices must be int, slice or str, not {kind}")
def __iter__(self) -> Iterator[tuple[list[float], float]]: yield from zip(self.X, self.y, strict=True)
houses = Dataset.from_csv( "data/houses.csv", target="price", features=["sqft", "bedrooms"])print(houses)print(len(houses), houses.n_samples)Dataset(n_samples=3000, features=['sqft', 'bedrooms'])3000 3000The first part is module 18’s class, unchanged: its checks, n_samples, n_features, column(), split_at() and from_csv(). The highlighted methods are new. __getitem__ checks the type of the key and answers three kinds of question. The repr shows the size and the names, not 3,000 rows: a repr should be short enough to read in a log line. __repr__ calls len(self), which runs __len__.
Step 2 — Get one sample by position
Section titled “Step 2 — Get one sample by position”print(houses[0])features, price = houses[-1]print(features, price)([2420.0, 4.0], 1097500.0)[1750.0, 2.0] 214500.0An integer key returns a (features, target) tuple, so you can unpack it. Negative indexes work for free: self.X[-1] is a list lookup, and lists understand them. An index past the end raises IndexError from the same list lookup.
Step 3 — Split with slices
Section titled “Step 3 — Split with slices”train, test = houses[:2400], houses[2400:]print(train)print(test)print(houses[::1000]["sqft"])Dataset(n_samples=2400, features=['sqft', 'bedrooms'])Dataset(n_samples=600, features=['sqft', 'bedrooms'])[2420.0, 1440.0, 1400.0]A slice returns a new Dataset, so train and test have all the methods. houses[:2400] and houses[2400:] give the same two parts as module 18’s houses.split_at(2400). The file is sorted by sold_date, so this split trains on the first 80% of the sales and tests on the most recent 20%, as a real price model must. houses[::1000] keeps every 1,000th house, and ["sqft"] then takes one column of that small dataset.
Step 4 — Read a column by name
Section titled “Step 4 — Read a column by name”sqft = houses["sqft"]print(len(sqft), min(sqft), max(sqft), sqft == houses.column("sqft"))print(f"median price {statistics.median(houses.y):,.0f}")3000 550.0 5710.0 Truemedian price 376,000A string key returns a feature column as a list, like df["sqft"] in pandas. It gives the same list as column(). The target stays in houses.y. The numbers match the data dictionary: 550 to 5,710 square feet, median price 376,000.
Step 5 — Loop over samples
Section titled “Step 5 — Loop over samples”for (sqft_value, bedrooms), price in test[:3]: print(f"{sqft_value:>6.0f} sqft {bedrooms:.0f} bd {price:>10,.0f}")total = sum(price for _, price in test)print(f"mean test price {total / len(test):,.0f}") 1860 sqft 3 bd 300,500 1950 sqft 2 bd 294,500 2840 sqft 5 bd 407,000mean test price 508,959for calls __iter__, which yields (features, target) pairs. The loop unpacks each pair and even the inner features list in one line. Generator expressions and sum() use the same method.
Step 6 — Check truth and membership
Section titled “Step 6 — Check truth and membership”print(bool(houses), ([1040.0, 3.0], 500500.0) in houses)True TrueDataset has no __bool__, so Python uses __len__, and a dataset with samples is truthy. It has no __contains__ either, so in falls back to __iter__ and compares each sample with ==. It finds house H0537, one of the injected price outliers. The scan reads up to 3,000 samples; for frequent lookups you would write __contains__ with a set.
Step 7 — Slice past the end
Section titled “Step 7 — Slice past the end”print(houses[3000:])ValueError: a Dataset needs at least one sampleThe slice itself works, but module 18’s __init__ refuses a dataset with no samples. So a Dataset is never empty, and bool(ds) is always True. A list slice past the end returns [] instead; here the stricter rule of module 18 wins.
Step 8 — Use a wrong key type
Section titled “Step 8 — Use a wrong key type”print(houses[1.5])TypeError: Dataset indices must be int, slice or str, not floatA float is neither a position, a slice nor a name, so __getitem__ raises TypeError with a clear message, the same error type that a list raises for [1, 2][1.5].
Common mistakes:
- Returning a plain list from a slice.
houses[:2400].feature_nameswould then fail. Return an object of the same class withtype(self)(...). - Raising your own error for an index past the end. Let the list raise
IndexError: theforfallback and many tools rely on that exact exception. - Making
__iter__returnselfwithout a__next__method.forthen raisesTypeError: iter() returned non-iterator. A generator method (yield from) always gives a fresh iterator. - Printing every row in
__repr__. A repr of 3,000 rows floods logs and the REPL. Show a summary.
Example 3 — Rank models on a leaderboard
Section titled “Example 3 — Rank models on a leaderboard”Goal: Fit three regression models on the houses data, score each one with R² and RMSE, and rank them. For R², higher is better. For RMSE, lower is better. The ranking code must not care which one it gets.
Step 1 — Write a score type with an order
Section titled “Step 1 — Write a score type with an order”@total_orderingclass ModelScore: """A model's score on one metric. a < b means: a is worse than b."""
def __init__( self, model: str, metric: str, value: float, greater_is_better: bool = True ) -> None: self.model = model self.metric = metric self.value = value self.greater_is_better = greater_is_better
def __repr__(self) -> str: return f"ModelScore({self.model!r}, {self.metric!r}, {self.value!r})"
def __str__(self) -> str: return f"{self.model:<36} {self.metric:>4} = {self.value:,.3f}"
def _rank_key(self) -> tuple[float, str]: signed = self.value if self.greater_is_better else -self.value return signed, self.model # ties: alphabetical model name decides
def _check(self, other: "ModelScore") -> None: if self.metric != other.metric: raise ValueError(f"cannot rank {self.metric} against {other.metric}")
def __eq__(self, other: object) -> bool: if not isinstance(other, ModelScore): return NotImplemented return (self.metric, self._rank_key()) == (other.metric, other._rank_key())
def __hash__(self) -> int: return hash((self.metric, self._rank_key()))
def __lt__(self, other: object) -> bool: if not isinstance(other, ModelScore): return NotImplemented self._check(other) return self._rank_key() < other._rank_key()The trick is _rank_key(). For a metric where lower is better, it flips the sign, so “less than” always means “worse than”. The model name breaks ties, so the order is total: for any two different scores, one is less than the other.
Step 2 — Score three models
Section titled “Step 2 — Score three models”X_train = [[v] for v in train["sqft"]] # LinearRegression takes 1 featureX_test = [[v] for v in test["sqft"]]y_train, y_test = train.y, test.y
r2_scores, rmse_scores = [], []for model in [DummyRegressor(), DummyRegressor("median"), LinearRegression()]: y_pred = model.fit(X_train, y_train).predict(X_test) name = repr(model) r2_scores.append(ModelScore(name, "r2", r2_score(y_test, y_pred))) rmse = math.sqrt(mean_squared_error(y_test, y_pred)) rmse_scores.append(ModelScore(name, "rmse", rmse, greater_is_better=False))print(r2_scores[2])print(rmse_scores[2])LinearRegression(fit_intercept=True) r2 = 0.561LinearRegression(fit_intercept=True) rmse = 229,936.245The repr of each estimator from Example 1 becomes the model name on the leaderboard. print() uses __str__, which aligns the columns with format specs. LinearRegression takes one feature, so the code wraps each sqft value in a one-item row.
Step 3 — Sort, and get the best with max()
Section titled “Step 3 — Sort, and get the best with max()”for board in (r2_scores, rmse_scores): for score in sorted(board, reverse=True): print(score) print("best:", max(board).model)LinearRegression(fit_intercept=True) r2 = 0.561DummyRegressor(strategy='mean') r2 = -0.014DummyRegressor(strategy='median') r2 = -0.161best: LinearRegression(fit_intercept=True)LinearRegression(fit_intercept=True) rmse = 229,936.245DummyRegressor(strategy='mean') rmse = 349,423.714DummyRegressor(strategy='median') rmse = 374,026.795best: LinearRegression(fit_intercept=True)sorted(board, reverse=True) puts the best score first on both boards, although the RMSE board sorts the raw numbers from low to high. max() returns the best score, because “greater” means “better” for every metric. The ranking code never asks which metric it has. The linear model on sqft beats both baselines. The baselines have a negative R²: they predict worse than the mean of the test prices itself. The test set holds the most recent sales, and prices rose over time (mean 508,959 in the test set, 476,466 in the whole file), so the training mean is too low.
Step 4 — Refuse to rank different metrics
Section titled “Step 4 — Refuse to rank different metrics”print(r2_scores[2] > rmse_scores[0])ValueError: cannot rank r2 against rmseAn R² of 0.561 and an RMSE of 349,424 cannot be compared, so _check() stops with a clear message. @total_ordering built > from __lt__, so the check runs for every operator.
Step 5 — Use the derived operators and the hash
Section titled “Step 5 — Use the derived operators and the hash”lin, mean_model, median_model = r2_scores[2], r2_scores[0], r2_scores[1]print(lin >= mean_model, median_model <= mean_model, lin != mean_model)again = ModelScore(lin.model, "r2", lin.value)print(again == lin, len({lin, again, mean_model}))True True TrueTrue 2>=, <= and != come from @total_ordering and from the default __ne__. A score recorded twice is equal to the first one and has the same hash, so a set keeps it once. ModelScore is a value object, immutable by convention: no code assigns to its fields after __init__, so hashing it is safe.
Common mistakes:
- Defining
__lt__as “smaller number”. For an error metric,max()then picks the worst model. Define the order by meaning (“worse than”), not by the raw number. - Writing
__lt__without__eq__.@total_orderingneeds both. Without your__eq__,<=uses identity and gives wrong answers for equal scores. - Letting ties be undecided. If neither
a < bnora == bnora > b, sorting still runs, but<=and>=disagree withsorted(). Break ties with a second key. - Returning
Falsefrom__lt__for an unknown type. ReturnNotImplemented, so Python can try the reflected operation and raise the rightTypeError.
Example 4 — Compute KNN distances with Vector operators
Section titled “Example 4 — Compute KNN distances with Vector operators”Goal: A KNN classifier measures the distance between customers. Write a Vector class with +, -, *, /, abs() and @, then use it to find the nearest neighbors of a new customer in data/customers.csv and to compute class centroids.
Step 1 — Write the Vector class
Section titled “Step 1 — Write the Vector class”from collections.abc import Iterable
class Vector: """An immutable vector of floats with math operators."""
def __init__(self, components: Iterable[float]) -> None: self._components = tuple(float(c) for c in components)
def __repr__(self) -> str: return f"Vector({list(self._components)!r})"
def __len__(self) -> int: return len(self._components)
def __iter__(self) -> Iterator[float]: return iter(self._components)
def __getitem__(self, index: int) -> float: return self._components[index]
def __eq__(self, other: object) -> bool: if not isinstance(other, Vector): return NotImplemented return self._components == other._components
def __hash__(self) -> int: return hash(self._components)
def _check(self, other: "Vector") -> None: if len(self) != len(other): raise ValueError(f"vector lengths differ: {len(self)} and {len(other)}")
def __add__(self, other: object) -> "Vector": if not isinstance(other, Vector): return NotImplemented self._check(other) return Vector(a + b for a, b in zip(self, other))
def __radd__(self, other: object) -> "Vector": return self if other == 0 else NotImplemented # lets sum() start at 0
def __sub__(self, other: object) -> "Vector": if not isinstance(other, Vector): return NotImplemented self._check(other) return Vector(a - b for a, b in zip(self, other))
def __mul__(self, scalar: object) -> "Vector": if not isinstance(scalar, int | float): return NotImplemented return Vector(a * scalar for a in self)
__rmul__ = __mul__
def __truediv__(self, scalar: object) -> "Vector": if not isinstance(scalar, int | float): return NotImplemented return Vector(a / scalar for a in self)
def __neg__(self) -> "Vector": return Vector(-a for a in self)
def __matmul__(self, other: object) -> float: if not isinstance(other, Vector): return NotImplemented self._check(other) return sum(a * b for a, b in zip(self, other))
def __abs__(self) -> float: return math.sqrt(self @ self)
def __bool__(self) -> bool: return any(self._components)
v = Vector([3, 4])print(v, len(v), abs(v), v @ v, -v)Vector([3.0, 4.0]) 2 5.0 25.0 Vector([-3.0, -4.0])abs(v) is the Euclidean norm, the length of the arrow from the origin to the point: . v @ v is the dot product of v with itself: . The norm reuses the dot product, because . The components live in a tuple, so a Vector never changes, and __hash__ is safe.
Step 2 — Turn customers into vectors
Section titled “Step 2 — Turn customers into vectors”raw = Dataset.from_csv( "data/customers.csv", target="churned", features=["tenure_months", "logins_last_30d"],)customers = Dataset(raw.X, [int(v) for v in raw.y], raw.feature_names) # 0/1sample = customers[::25] # every 25th customer: 200 of 5,000points = [(Vector(features), label) for features, label in sample]print(len(points), points[0])print("churn rate:", sum(label for _, label in points) / len(points))200 (Vector([72.0, 17.0]), 0)churn rate: 0.175Each customer becomes a 2-dimensional vector: months of tenure and logins in the last 30 days. from_csv() reads churned as a float, so the second line rebuilds the dataset with int labels 0 and 1, as module 19 does. The Dataset slice and the for loop come from Example 2. The sample churn rate, 17.5%, is close to the 19.3% of the full file.
Step 3 — Measure distances with abs(a - b)
Section titled “Step 3 — Measure distances with abs(a - b)”query = Vector([4, 2]) # a new customer: 4 months, 2 loginsfirst = points[0][0]print(query - first, abs(query - first))print(math.isclose(abs(query - first), math.dist(query, first)))Vector([-68.0, -15.0]) 69.63476143421474TrueThe distance between two points is the norm of their difference: . query - first calls __sub__, and abs() calls __abs__. math.dist() gives the same number, and it accepts two Vector objects because it only needs iterables of numbers.
Step 4 — Find the 5 nearest neighbors and vote
Section titled “Step 4 — Find the 5 nearest neighbors and vote”nearest = sorted(points, key=lambda p: abs(p[0] - query))[:5]for point, label in nearest: print(point, f"distance {abs(point - query):.2f}", "churned" if label else "stayed")votes = Counter(label for _, label in nearest)print("prediction:", "churn" if votes[1] > votes[0] else "stay", dict(votes))Vector([5.0, 2.0]) distance 1.00 churnedVector([3.0, 2.0]) distance 1.00 churnedVector([4.0, 0.0]) distance 2.00 stayedVector([3.0, 4.0]) distance 2.24 churnedVector([3.0, 4.0]) distance 2.24 stayedprediction: churn {1: 3, 0: 2}Three of the five nearest customers churned, so the vote predicts churn. The key function reads like the formula: the distance from each point to the query. This is the core of KNNClassifier. The mini-project replaces math.dist in minilearn with this Vector code.
Step 5 — Compute centroids with sum() and /
Section titled “Step 5 — Compute centroids with sum() and /”churned = [p for p, label in points if label == 1]stayed = [p for p, label in points if label == 0]centroid_churned = sum(churned) / len(churned)centroid_stayed = sum(stayed) / len(stayed)print(centroid_churned, centroid_stayed)print(f"{abs(query - centroid_churned):.1f} vs {abs(query - centroid_stayed):.1f}")midpoint = 0.5 * (centroid_churned + centroid_stayed)print(midpoint)Vector([10.8, 9.142857142857142]) Vector([25.884848484848487, 10.66060606060606])9.9 vs 23.5Vector([18.342424242424244, 9.901731601731601])A centroid is the mean point of a group: add the vectors, then divide by their count. sum(churned) starts with 0 + churned[0], which works only because of __radd__. Churned customers have a much shorter tenure on average. The query is closer to the churned centroid, which agrees with the KNN vote. 0.5 * (...) uses __rmul__, because a float is on the left.
Step 6 — Add vectors of different lengths
Section titled “Step 6 — Add vectors of different lengths”print(query + Vector([1, 2, 3]))ValueError: vector lengths differ: 2 and 3Adding vectors of different lengths is a data bug, so _check() raises a ValueError with both lengths.
Step 7 — Multiply two vectors
Section titled “Step 7 — Multiply two vectors”print(query * query)TypeError: unsupported operand type(s) for *: 'Vector' and 'Vector'Vector * Vector has no single meaning (NumPy multiplies element by element, a mathematician might mean the dot product), so __mul__ returns NotImplemented and Python raises TypeError. Use @ for the dot product.
Common mistakes:
- Forgetting
__rmul__.v * 2works, but2 * vraisesTypeError: unsupported operand type(s) for *: 'int' and 'Vector'. - Forgetting
__radd__.sum(vectors)fails at0 + vectors[0]. Either write__radd__, or pass a start value:sum(vectors, start=Vector([0, 0])). - Comparing distances of unscaled features. Tenure (0 to 72) and logins (0 to 60) have similar ranges, but not similar spreads: their standard deviations are about 20 and 7 (module 19). So tenure dominates the distances in this example. Scale first with
StandardScaler, as Example 6 does. - Changing
selfinside__add__. An operator must return a new object and leave both operands unchanged.
Example 5 — Call scorers and models like functions
Section titled “Example 5 — Call scorers and models like functions”Goal: scikit-learn evaluates models with scorers: callable objects such as scorer(model, X, y). Write one, count its calls, and make a model callable so that model(X) means model.predict(X), as in PyTorch.
Step 1 — Write a scorer class
Section titled “Step 1 — Write a scorer class”from collections.abc import Callable
def root_mean_squared_error(y_true: list[float], y_pred: list[float]) -> float: return math.sqrt(mean_squared_error(y_true, y_pred))
class Scorer: """Score a fitted model on (X, y). Greater is always better."""
def __init__(self, metric: Callable[[list, list], float], sign: int = 1) -> None: self.metric = metric self.sign = sign # -1 flips an error metric: greater is better self.n_calls = 0
def __repr__(self) -> str: return f"Scorer({self.metric.__name__}, sign={self.sign})"
def __call__( self, model: BaseEstimator, X: list[list[float]], y: list[float] ) -> float: self.n_calls += 1 return self.sign * self.metric(y, model.predict(X))
r2 = Scorer(r2_score)neg_rmse = Scorer(root_mean_squared_error, sign=-1)print(r2, neg_rmse)Scorer(r2_score, sign=1) Scorer(root_mean_squared_error, sign=-1)The scorer keeps its metric and its sign as attributes, and it counts its own calls. A scikit-learn scorer works the same way: get_scorer("neg_root_mean_squared_error") returns a callable object, and it flips the sign so that greater is always better.
Step 2 — Pick the best model with the scorers
Section titled “Step 2 — Pick the best model with the scorers”fitted = [m.fit(X_train, y_train) for m in (DummyRegressor(), LinearRegression())]for scorer in (r2, neg_rmse): best = max(fitted, key=lambda m: scorer(m, X_test, y_test)) print(f"{scorer!r:<45} best: {best}")print(r2.n_calls, neg_rmse.n_calls)Scorer(r2_score, sign=1) best: LinearRegression(fit_intercept=True)Scorer(root_mean_squared_error, sign=-1) best: LinearRegression(fit_intercept=True)2 2scorer(m, X_test, y_test) runs Scorer.__call__. Both scorers agree on the best model. Each one scored both models once, so each counted 2 calls. The !r flag in the f-string shows the scorer’s repr; the format spec :<45 then pads it.
Step 3 — Make a model callable
Section titled “Step 3 — Make a model callable”class CallableMixin: """model(X) means model.predict(X), like nn.Module.__call__ runs forward()."""
def __call__(self, X: list[list[float]]) -> list[Any]: return self.predict(X)
class PriceModel(CallableMixin, LinearRegression): """A linear price model that you can call like a function."""
price_model = PriceModel().fit(X_train, y_train)print(price_model)print([round(p) for p in price_model([[1500.0], [2500.0]])])print(price_model(X_test) == price_model.predict(X_test))PriceModel(fit_intercept=True)[355368, 671656]TrueThe mixin adds one method, and PriceModel inherits fit, predict and __repr__ from its parents. A call such as price_model(X) reads like a mathematical function . Each extra 1,000 square feet adds about 316,000 to the predicted price.
Step 4 — Check what is callable
Section titled “Step 4 — Check what is callable”things = [r2_score, r2, price_model, PriceModel, houses]print([callable(t) for t in things])[True, True, True, True, False]A function, a Scorer, a callable model and a class are all callable: calling a class creates an instance. A Dataset has no __call__, so it is not. callable() is how frameworks check a callback before they store it.
Common mistakes:
- Defining
__call__with no clear main action.dataset()means nothing to a reader. Keep__call__for objects that are “a function with settings”: scorers, transforms, models. - Putting heavy work in
__call__and calling the object in a loop by accident. A call looks cheap. Name expensive work as a method, such asfit(). - Forgetting that
__call__is looked up on the class.scorer.__call__ = other_functiondoes not changescorer(...).
Example 6 — Try settings safely with a context manager
Section titled “Example 6 — Try settings safely with a context manager”Goal: Try other values of n_neighbors on a fitted KNN model of customer churn, and be sure that the model gets its original settings back, even when the experiment crashes.
Step 1 — Fit a churn model
Section titled “Step 1 — Fit a churn model”train_c = customers[::5] # rows 0, 5, 10, ...valid_c = customers[2::25] # rows 2, 27, 52, ...: never in train_cscaler = StandardScaler().fit(train_c.X)X_train_c, X_valid_c = scaler.transform(train_c.X), scaler.transform(valid_c.X)knn = KNNClassifier(n_neighbors=15).fit(X_train_c, train_c.y)print(knn, knn.score(X_valid_c, valid_c.y))print(f"baseline (always 'stay'): {1 - sum(valid_c.y) / len(valid_c):.3f}")KNNClassifier(n_neighbors=15) 0.845baseline (always 'stay'): 0.820The two slices take every 5th customer for training and every 25th customer, shifted by 2, for validation. They never share a row. A validation set is the data you use to compare settings of a model; the final test set stays untouched until the very end (module 37). The scaler gives tenure and logins the same weight. KNN with 15 neighbors beats the baseline that predicts “stay” for everyone.
Step 2 — Write the context manager
Section titled “Step 2 — Write the context manager”class TemporaryParams: """Set estimator parameters inside a with block, then restore them."""
def __init__(self, estimator: BaseEstimator, **params: Any) -> None: self.estimator = estimator self.params = params self._saved: dict[str, Any] = {}
def __repr__(self) -> str: args = ", ".join(f"{k}={v!r}" for k, v in self.params.items()) return f"TemporaryParams({self.estimator!r}, {args})"
def __enter__(self) -> BaseEstimator: current = self.estimator.get_params() unknown = sorted(set(self.params) - set(current)) if unknown: # check before changing anything raise ValueError(f"unknown parameters: {unknown}") self._saved = {name: current[name] for name in self.params} self.estimator.set_params(**self.params) return self.estimator
def __exit__(self, exc_type, exc_value, traceback) -> None: self.estimator.set_params(**self._saved) # runs even after an error__enter__ saves the current values of the parameters it will change, sets the new values and returns the estimator for as. __exit__ restores the saved values. It returns None, so an exception from the block continues after the cleanup. The check for unknown names runs before any change, because __exit__ does not run when __enter__ itself raises.
Step 3 — Run an experiment inside the block
Section titled “Step 3 — Run an experiment inside the block”with TemporaryParams(knn, n_neighbors=1) as model: print("inside: ", model, model.score(X_valid_c, valid_c.y))print("after: ", knn, knn.score(X_valid_c, valid_c.y))inside: KNNClassifier(n_neighbors=1) 0.75after: KNNClassifier(n_neighbors=15) 0.845Inside the block, the same model object uses 1 neighbor and scores much worse: one neighbor follows the noise. After the block, it is back at 15 neighbors. KNNClassifier reads n_neighbors at prediction time, so no refit is needed.
Step 4 — Crash inside the block
Section titled “Step 4 — Crash inside the block”with TemporaryParams(knn, n_neighbors=5) as model: model.score(X_valid_c, train_c.y) # bug: the training targetsValueError: lengths differ: 1000 vs 200The bug passes 1,000 training targets with 200 validation rows, so the length check in accuracy_score raises.
Step 5 — Check the model after the crash
Section titled “Step 5 — Check the model after the crash”print(knn)KNNClassifier(n_neighbors=15)The with statement still called __exit__, and the model is back at 15 neighbors. Without the context manager, the crash would leave the model at 5 neighbors, and a later report would silently use the wrong setting.
Step 6 — Scan several settings
Section titled “Step 6 — Scan several settings”for k in (1, 5, 15, 25, 45): with TemporaryParams(knn, n_neighbors=k) as model: print(f"n_neighbors={k:<3} accuracy={model.score(X_valid_c, valid_c.y):.3f}")print(knn)n_neighbors=1 accuracy=0.750n_neighbors=5 accuracy=0.815n_neighbors=15 accuracy=0.845n_neighbors=25 accuracy=0.830n_neighbors=45 accuracy=0.845KNNClassifier(n_neighbors=15)This loop is a small validation curve: one score per value of a hyperparameter (module 37 draws them properly). Accuracy rises from 1 to 15 neighbors and then levels off. A 200-row validation set is small, so differences of one or two percentage points are noise. Choose n_neighbors on validation data like this, never on the final test set: a test score used to pick a setting is no longer an honest estimate. Module 11’s contextlib.contextmanager could write the same manager as a generator function; the class form keeps the saved values in plain attributes that you can inspect.
Common mistakes:
- Restoring the values only after a normal exit. Put the cleanup in
__exit__(or in afinally), never as the last line of the block. - Returning
Truefrom__exit__by accident. That suppresses every exception in the block, and the bug disappears silently. - Raising inside
__enter__after a partial change.__exit__does not run then. Validate first, then change. - Forgetting
return self.estimatorin__enter__. The name afterasis thenNone.
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
No __repr__ |
<__main__.Money object at 0x...> in logs and lists |
Write __repr__; it is also the fallback for str() |
Only __str__, no __repr__ |
print(x) is fine, but print([x]) shows the address |
Write __repr__ first |
__eq__ without __hash__ |
TypeError: unhashable type: 'Money' |
Add __hash__ from the same fields, for immutable classes only |
__hash__ from fields that change |
An object in a set is not found after a change | Hash only immutable objects; build a key tuple for mutable ones |
__eq__ returns False or raises for other types |
Reflected comparisons break; x == "text" crashes |
return NotImplemented |
__lt__ without @total_ordering |
TypeError: '<=' not supported between instances of ... |
Add @total_ordering and __eq__ |
No __radd__ |
sum(items): TypeError: unsupported operand type(s) for +: 'int' and 'Money' |
__radd__ that accepts 0, or sum(items, start=zero) |
No __rmul__ |
2 * v: TypeError: unsupported operand type(s) for *: 'int' and 'Vector' |
__rmul__ = __mul__ for commutative operations |
raise NotImplemented |
TypeError: exceptions must derive from BaseException |
return NotImplemented |
__len__ returns a float |
TypeError: 'float' object cannot be interpreted as an integer |
Return an int |
__iter__ returns self with no __next__ |
TypeError: iter() returned non-iterator of type ... |
Make __iter__ a generator (yield from) |
__getitem__ ignores slices |
ds[:10] returns a tuple of lists, and the next method call fails |
Check isinstance(key, slice) and return the same class |
__bool__ returns len(...) |
TypeError: __bool__ should return bool, returned int |
Return a bool, or define only __len__ |
No return in __enter__ |
as name binds None |
Return self or the managed object |
| An operator with a surprising meaning | Readers misread the code | Use a named method instead |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Web development: Django models compare by primary key in
__eq__and print as<User: ...>through__repr__. SQLAlchemy overloads==and<on columns, soUser.age >= 18builds SQL instead of abool. - Standard library:
pathlib.Pathoverloads/(__truediv__) to join paths,datetimeoverloads-to give atimedelta, anddecimal.Decimalis an exact money type with every arithmetic dunder. - Testing:
pytest.approx(0.3) == 0.1 + 0.2works through__eq__.unittest.mock.MagicMockimplements__call__,__enter__,__len__and the rest, so it can stand in for almost any object. - Tooling and automation: command-line frameworks register callable objects as commands, and lock, transaction and temporary-directory helpers are context managers.
Summary
Section titled “Summary”- Python syntax calls special methods on the class of the object:
len(x)runstype(x).__len__(x). Writing them makes your class behave like a built-in. - Always write
__repr__, unambiguous and ideally valid code. Write__str__only for a friendlier user text. Use!rinside a repr. __eq__compares by value; returnNotImplementedfor unknown types. Defining__eq__sets__hash__toNone. Add__hash__from the same fields only for immutable value objects.@total_orderingplus__eq__and__lt__give all six comparisons. Give a class an order only when it has one natural order; otherwise usekey=.__len__,__getitem__(int, slice, name),__iter__and__contains__make a container. Slices should return the same class.__bool__falls back to__len__.__call__makes a function with settings and state.__enter__and__exit__make cleanup run even after an error.- Arithmetic dunders return a new object or
NotImplemented. Reflected methods (__radd__,__rmul__) handle0 + xinsum()and2 * v.
Self-check questions
Section titled “Self-check questions”Q1. You run len(log). Which method does Python call, and where does it look for it?
Answer
__len__. Python looks it up on the class: type(log).__len__(log). A __len__ attribute set on the instance is ignored by len().
Q2. A class defines only __str__. What does print([obj]) show, and why?
Answer
Something like [<__main__.Reading object at 0x...>]. A list shows the repr of each item, and the class has no __repr__, so the default repr with the address appears. str() falls back to __repr__, but repr() never falls back to __str__.
Q3. What do f"{name}" and f"{name!r}" show when name = "median"?
Answer
median and 'median'. The !r flag calls repr(), which adds quotes to a string. Use it inside __repr__ so that DummyRegressor(strategy='median') stays valid code.
Q4. You add __eq__ to a class. Now set(items) raises TypeError: unhashable type. Why does Python do this?
Answer
Defining __eq__ without __hash__ sets __hash__ to None. The default hash is based on identity, so two equal objects would have different hashes. That breaks the rule “equal objects have equal hashes”, and sets and dicts would give wrong answers. Python makes the class unhashable instead. Add __hash__ from the same fields if the objects never change.
Q5. Why should __eq__ return NotImplemented instead of False for an unknown type?
Answer
NotImplemented tells Python to ask the other operand (its reflected __eq__). Only if both decline does Python fall back to identity. Returning False ends the search early, so a class that knows how to compare with yours never gets a chance.
Q6. A class has __eq__ and __lt__. Which comparisons work without @total_ordering, and which fail?
Answer
==, != (the inverse of __eq__), < and > work. a > b works through the reflection b < a. <= and >= raise TypeError, because nothing defines __le__ or __ge__. @total_ordering adds them.
Q7. sum(lines) on a list of Money objects raises TypeError: unsupported operand type(s) for +: 'int' and 'Money'. What is missing, and what are the two fixes?
Answer
sum() starts at 0, and 0 + Money needs Money.__radd__. Fix 1: write __radd__ that returns self when the other operand is 0. Fix 2: give sum() a start value, sum(lines, start=Money(0)).
Q8. A class has __getitem__ that accepts 0, 1, 2… and raises IndexError at the end, but no __iter__ and no __contains__. Do for and in work?
Answer
Yes. for falls back to calling __getitem__(0), __getitem__(1) and so on until IndexError. in falls back to the same loop and compares each item with ==. Both are linear scans; write __iter__ for clarity and __contains__ for a faster test.
Q9. When is a Dataset object falsy? It has __len__ but no __bool__.
Answer
When len(ds) is 0. Python tries __bool__ first, then __len__. An object with neither method is always truthy.
Q10. In TemporaryParams, why does the restore code go in __exit__ and not at the end of the with block?
Answer
__exit__ runs when the block ends in any way, including an exception. Code at the end of the block is skipped when a line above it raises, and the model would keep the temporary settings.
Q11. Why is it correct that minilearn estimators are unhashable, while Vector and Money are hashable?
Answer
Estimators change: set_params() and fit() modify them, so a hash built from their parameters would change and the object would get lost in a set. Vector and Money are value objects: no code changes their fields after __init__ (Vector keeps its components in a private tuple; Money is immutable by convention), so their hash stays valid. Read-only properties (exercise M20-C07) or @dataclass(frozen=True) (module 21) enforce this.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Exercises: 26 exercises on every special method of this module, from warm-up to challenge.
- Mini-project: give
minilearnaPipelinethat you can index, slice and loop over, and aVectorfor KNN distances. - Cheat sheet: the full table of special methods, with what triggers each one and an example.
- Next module: 21. Dataclasses, enums and slots writes
__init__,__repr__,__eq__and the ordering methods for you with@dataclass, and addsEnum,NamedTupleand__slots__.