The essentials of module 20 on one page. Every runnable block on this page is checked against its output.
I want to…
Use…
Example
show an object clearly in logs and the REPL
__repr__
KNNClassifier(n_neighbors=15)
show a friendly text in a report
__str__
S1: 21.7 °C
support format specs in f-strings
__format__(self, spec)
f"{price:,.2f}"
force the repr inside an f-string
!r
f"{name!r}" → 'median'
compare two objects by value
__eq__, return NotImplemented for other types
Money(5) == Money(5)
put objects in a set or use them as dict keys
__hash__ from the same fields as __eq__
hash((self.cents, self.currency))
keep a mutable class out of sets
define __eq__ only (__hash__ becomes None)
estimators
sort, min(), max()
__lt__ + __eq__ + @functools.total_ordering
sorted(scores)
sort by something that is not the natural order
key= instead of __lt__
sorted(rows, key=lambda r: r.celsius)
len(x)
__len__ (return an int ≥ 0)
len(dataset)
x[i], x[a:b], x["name"]
__getitem__(self, key); test isinstance(key, slice)
ds[:2400], ds["sqft"]
for item in x
__iter__ as a generator (yield from ...)
for row, target in ds
item in x fast or for infinite sets
__contains__
21.7 in Interval(19, 23)
control if x:
__bool__ (return a bool), or only __len__
bool(Money(0)) → False
call an object like a function
__call__
scorer(model, X, y)
set up and always clean up
__enter__ / __exit__
with TemporaryParams(knn, n_neighbors=1):
a + b, a - b, a * k, a @ b, abs(a)
__add__, __sub__, __mul__, __matmul__, __abs__
abs(u - v)
2 * v, 0 + x
reflected __rmul__, __radd__
__rmul__ = __mul__
make sum() work
__radd__ that accepts 0, or sum(xs, start=zero)
sum(lines)
decline an operand type
return NotImplemented
Python tries the other side
a full read-only sequence from two methods
subclass collections.abc.Sequence
__getitem__ + __len__
a dict that returns a default for missing keys
subclass dict and write __missing__
Counter, defaultdict
Method → triggered by → example. The examples use the classes of the lesson.
Method
Triggered by
Example
__new__(cls, ...)
Cls(...), before __init__; creates the object
immutable subclasses of int, str, tuple
__init__(self, ...)
Cls(...), after __new__; fills the object
Money(1349)
__del__(self)
the object is garbage-collected (timing not guaranteed)
rarely needed; use with for cleanup
__repr__(self)
repr(x), REPL echo, items in containers, f"{x!r}", f"{x=}"
Money(1349, 'USD')
__str__(self)
str(x), print(x), f"{x}"; falls back to __repr__
13.49 USD
__format__(self, spec)
format(x, spec), f"{x:spec}"
f"{price:,.2f}"
__bytes__(self)
bytes(x)
binary serialization
__bool__(self)
bool(x), if x:, while x:, and/or/not
zero money is falsy
__int__, __float__, __complex__
int(x), float(x), complex(x)
float(Money(250))
__index__(self)
x used as an index or in range(), bin(), hex()
integer-like types
__round__(self, n)
round(x, n)
round(money, 1)
__trunc__, __floor__, __ceil__
math.trunc(x), math.floor(x), math.ceil(x)
numeric types
__hash__(self)
hash(x), set members, dict keys
hash((self.sensor_id, self.celsius))
__fspath__(self)
open(x), os.fspath(x), pathlib.Path(x)
a class that names a file
Method
Triggered by
Reflection
Example
__eq__(self, other)
a == b, in on lists, list.index, list.count
b.__eq__(a)
same configuration
__ne__(self, other)
a != b; default: inverts __eq__
b.__ne__(a)
rarely written
__lt__(self, other)
a < b, sorted(), min(), max(), heapq
b.__gt__(a)
worse score
__le__(self, other)
a <= b
b.__ge__(a)
from @total_ordering
__gt__(self, other)
a > b
b.__lt__(a)
from @total_ordering
__ge__(self, other)
a >= b
b.__le__(a)
from @total_ordering
Method
Triggered by
Example
__len__(self)
len(x); truth when __bool__ is missing
len(houses) → 3000
__getitem__(self, key)
x[key], x[a:b] (a slice object), x[i, j] (a tuple)
houses[0], houses[:2400], cm[1, 0]
__setitem__(self, key, value)
x[key] = value
a mutable table
__delitem__(self, key)
del x[key]
a mutable table
__missing__(self, key)
d[key] on a dict subclass, for a missing key
defaultdict, Counter
__iter__(self)
for, list(x), sum(x), zip(), unpacking a, b = x
for row, target in ds
__next__(self)
next(it); only on iterators
generator objects
__reversed__(self)
reversed(x)
newest readings first
__contains__(self, item)
item in x, item not in x
"age" in store
__length_hint__(self)
operator.length_hint(x), list pre-sizing
lazy iterators
Method
Triggered by
Example
__call__(self, ...)
x(...)
scorer(model, X, y), clip(21.7)
__enter__(self)
the start of with x as name:; its result goes to name
TemporaryParams.__enter__ returns the model
__exit__(self, exc_type, exc, tb)
the end of the with block, also after an exception; True suppresses
restore the parameters
__aenter__, __aexit__
async with x:
database sessions in asyncio
__getattr__(self, name)
x.name when normal lookup fails
proxies, lazy attributes
__getattribute__(self, name)
every x.name (avoid overriding)
tracing tools
__setattr__(self, name, value)
x.name = value
read-only objects
__delattr__(self, name)
del x.name
__dir__(self)
dir(x), tab completion
__copy__, __deepcopy__(self, memo)
copy.copy(x), copy.deepcopy(x)
share or copy fitted state
__getstate__, __setstate__
pickle.dumps(x), pickle.loads(...)
drop an open file before saving
__init_subclass__(cls)
a subclass is created
register every estimator class
__class_getitem__(cls, item)
Cls[int] in type hints
list[float]
Operator
Method
Reflected (x on the right)
In place
a + b
__add__
__radd__
a += b → __iadd__
a - b
__sub__
__rsub__
__isub__
a * b
__mul__
__rmul__
__imul__
a / b
__truediv__
__rtruediv__
__itruediv__
a // b
__floordiv__
__rfloordiv__
__ifloordiv__
a % b
__mod__
__rmod__
__imod__
divmod(a, b)
__divmod__
__rdivmod__
a ** b, pow(a, b)
__pow__
__rpow__
__ipow__
a @ b
__matmul__
__rmatmul__
__imatmul__
a & b, a | b, a ^ b
__and__, __or__, __xor__
__rand__, __ror__, __rxor__
__iand__, __ior__, __ixor__
a << b, a >> b
__lshift__, __rshift__
__rlshift__, __rrshift__
__ilshift__, __irshift__
-a, +a, abs(a), ~a
__neg__, __pos__, __abs__, __invert__
| is set union and dict merge (d1 | d2), and it builds union types (int | None). &, | and ~ combine boolean masks in pandas and NumPy.
def __init__ (self, sensor_id: str , celsius: float ) -> None :
self .sensor_id, self .celsius = sensor_id, celsius
def __repr__ (self) -> str : # for developers: valid code
return f "Reading( {self .sensor_id !r } , {self .celsius !r } )"
def __str__ (self) -> str : # for users: readable
return f " {self .sensor_id } : {self .celsius :.1f } °C"
print (r, repr (r), [r]) # print -> str; containers -> repr
print ( f " { r !s } | { r !r } | { r = } " ) # conversion flags and the debug form
S1: 21.7 °C Reading('S1', 21.7) [Reading('S1', 21.7)]
S1: 21.7 °C | Reading('S1', 21.7) | r=Reading('S1', 21.7)
Rule
Why
Always write __repr__.
str() falls back to it; nothing falls back to __str__.
Make the repr look like the constructor call.
You can paste it back into code, and eval(repr(x)) == x when practical.
Use !r for every field inside a repr.
Strings keep their quotes.
Keep the repr short for big objects.
Show sizes and names, not 3,000 rows.
Use type(self).__name__, not a hard-coded name.
Subclasses show their own name.
__format__ adds format specs. The default object.__format__ raises TypeError for any non-empty spec:
def __init__ (self, cents: int ) -> None :
def __format__ (self, spec: str ) -> str :
return format ( self .cents / 100 , spec or ".2f" ) + " USD"
print ( f " { Money( 123456 ) :,.2f } " , f " { Money( 5 ) } " , format (Money( 99 )))
1,234.56 USD 0.05 USD 0.99 USD
def __init__ (self, sensor_id: str , celsius: float ) -> None :
self .sensor_id, self .celsius = sensor_id, celsius
def _key (self) -> tuple[ str , float ]:
return self .sensor_id, self .celsius
def __eq__ (self, other: object ) -> bool :
if not isinstance (other, Reading):
return NotImplemented # let Python try the other side
return self ._key() == other._key()
def __hash__ (self) -> int : # the same fields as __eq__
readings = [Reading( "S1" , 21.7 ), Reading( "S2" , 19.25 ), Reading( "S1" , 21.7 )]
print ( len ( set (readings)), Reading( "S1" , 21.7 ) in readings, Reading( "S1" , 21.7 ) == "S1" )
Class defines
==
__hash__
Hashable?
neither
identity (is)
identity-based
yes
__eq__ only
your rule
set to None
no: TypeError: unhashable type
__eq__ and __hash__
your rule
your rule
yes, if the fields never change
__hash__ = None explicitly
None
no (documents the intent)
The hash contract: if a == b, then hash(a) == hash(b). Equal hashes do not imply equality (collisions are allowed). Never print hash values of strings: they change between runs.
from functools import total_ordering
@total_ordering # writes <=, > and >= from __eq__ and __lt__
def __init__ (self, text: str ) -> None :
self .parts = tuple ( int (p) for p in text.split( "." ))
def __repr__ (self) -> str :
return f "Version( { '.' .join( map ( str , self .parts)) !r } )"
def __eq__ (self, other: object ) -> bool :
if not isinstance (other, Version):
return self .parts == other.parts
def __hash__ (self) -> int :
def __lt__ (self, other: object ) -> bool :
if not isinstance (other, Version):
return self .parts < other.parts
print ( sorted ( map (Version, [ "1.10.0" , "1.9.3" , "1.4.0" ])))
print (Version( "1.10" ) >= Version( "1.9" ), max ( map (Version, [ "2.0" , "1.10" ])))
[Version('1.4.0'), Version('1.9.3'), Version('1.10.0')]
Fact
Detail
sorted(), min(), max(), list.sort(), heapq
need only <
a > b without __gt__
Python tries the reflection b < a
<=, >= without __le__, __ge__
TypeError; use @total_ordering
@total_ordering
needs __eq__ and one of __lt__, __le__, __gt__, __ge__; derived methods are a bit slower
An order must be total and agree with ==
if neither a < b nor b < a, then a == b
“Best” first for any metric
define < as “worse than”, so max() is the best (lesson Example 3)
from collections.abc import Iterator
def __init__ (self, values: list[ float ]) -> None :
def __len__ (self) -> int :
def __getitem__ (self, key: int | slice ) -> "float | SensorLog" :
if isinstance (key, slice ):
return type ( self )( self .values[key]) # a slice keeps the class
return self .values[key] # IndexError comes from the list
def __iter__ (self) -> Iterator[ float ]:
yield from self .values # a fresh iterator for every loop
log = SensorLog([ 19.5 , 20.7 , 20.1 , 21.2 ])
print ( len (log), log[ - 1 ], log[ 1 : 3 ].values, max (log), 20.1 in log, bool (log[ 4 :]))
4 21.2 [20.7, 20.1] 21.2 True False
Missing method
Fallback
__iter__
__getitem__(0), (1), … until IndexError
__contains__
a loop over __iter__ with ==
__bool__
__len__() != 0, otherwise always True
__reversed__
__len__ + __getitem__ with indexes from the end
__ne__
not __eq__
Base class from collections.abc
You write
You get for free
Iterable
__iter__
isinstance(x, Iterable) checks
Container
__contains__
Sized
__len__
Sequence
__getitem__, __len__
__contains__, __iter__, __reversed__, index, count
MutableSequence
the above + __setitem__, __delitem__, insert
append, extend, pop, remove, +=
Mapping
__getitem__, __len__, __iter__
__contains__, keys, items, values, get, __eq__
MutableMapping
the above + __setitem__, __delitem__
pop, popitem, setdefault, update, clear
def __init__ (self, metric, sign: int = 1 ) -> None :
self .metric, self .sign, self .n_calls = metric, sign, 0
def __call__ (self, model, X, y) -> float : # scorer(model, X, y)
return self .sign * self .metric(y, model.predict(X))
def __init__ (self, estimator, ** params) -> None :
self .estimator, self .params, self ._saved = estimator, params, {}
def __enter__ (self): # validate first: __exit__ does not run if this raises
current = self .estimator.get_params()
self ._saved = {k: current[k] for k in self .params}
self .estimator.set_params( ** self .params)
return self .estimator # bound to the name after "as"
def __exit__ (self, exc_type, exc, tb) -> None : # runs even after an error
self .estimator.set_params( ** self ._saved) # None: exceptions continue
__exit__ returns
Effect
None / False
an exception from the block propagates after cleanup
True
the exception is suppressed (use with care)
Callable kinds
callable(x)
function, lambda, method, built-in
True
class (calling it creates an instance)
True
instance of a class with __call__
True
other instances
False
def __add__ (self, other: object ) -> object :
return NotImplemented # "I do not know this type"
def __radd__ (self, other: object ) -> str :
return f "Right.__radd__( {type (other). __name__} )"
print (Left() + Right(), 0 + Right())
Right.__radd__(Left) Right.__radd__(int)
How Python evaluates a + b:
If type(b) is a subclass of type(a) and overrides __radd__, try b.__radd__(a) first.
Otherwise call a.__add__(b). A result other than NotImplemented is the answer.
Then try b.__radd__(a).
If both return NotImplemented (or are missing), raise TypeError: unsupported operand type(s) for +.
Rule
Example
Return a new object; never change the operands
Vector(a + b for a, b in zip(self, other))
Return NotImplemented, never raise TypeError, for unknown types
Money + 5 → Python raises the TypeError
Raise ValueError for a supported type with bad values
vectors of different lengths, different currencies
Commutative operation: share the method
__rmul__ = __mul__
sum() starts at 0
__radd__ returns self when other == 0
+= falls back to +
immutable classes skip __iadd__; mutable accumulators return self from it
Reject bool where only numbers make sense
isinstance(k, bool) or not isinstance(k, int | float)
A value object (immutable, comparable, hashable, with math):
def __init__ (self, cents: int , currency: str = "USD" ) -> None :
self ._cents, self ._currency = cents, currency # read-only by convention
def __repr__ (self) -> str : ... # Money(1349, 'USD')
def __eq__ (self, other: object ) -> bool : ... # NotImplemented for other types
def __hash__ (self) -> int : ... # hash((self._cents, self._currency))
def __lt__ (self, other: object ) -> bool : ... # same currency only
def __add__ (self, other: object ) -> "Money" : ... # a new Money
def __radd__ (self, other: object ) -> "Money" : ... # 0 + money for sum()
def __mul__ (self, k: object ) -> "Money" : ... # money * quantity
def __bool__ (self) -> bool : ... # zero is falsy
A collection (sized, indexable, sliceable, iterable):
def __repr__ (self) -> str : ... # Dataset(n_samples=3000, features=[...])
def __len__ (self) -> int : ...
def __getitem__ (self, key): ... # int -> sample, slice -> Dataset, str -> column
def __iter__ (self): ... # yield from zip(self.X, self.y)
def __contains__ (self, item) -> bool : ... # only if a faster test exists
Module 21’s @dataclass writes __init__, __repr__ and __eq__ for you; order=True adds the comparisons, and frozen=True adds __hash__ and blocks assignment.
Special methods are looked up on the class: obj.__len__ = ... does not change len(obj).
Defining __eq__ sets __hash__ to None. The class is unhashable until you write __hash__.
Hash only immutable objects. A changed field moves the object to another bucket, and x in s becomes False.
Return NotImplemented (a value), not NotImplementedError (an exception), and never raise NotImplemented.
print([x]) uses __repr__, even when __str__ exists.
__len__ must return an int ≥ 0, and __bool__ must return a bool; anything else raises TypeError or ValueError.
__iter__ returning self without __next__ raises TypeError: iter() returned non-iterator. Use a generator.
A slice reaches __getitem__ as a slice object. Return the same class, not a plain list.
__getitem__ that returns a default for missing keys breaks the in fallback: every key looks present. Write __contains__ too.
__eq__ that returns something other than a bool (like pandas masks) makes if a == b: and x in list_of_columns misbehave. pandas raises ValueError in __bool__ for this reason.
@total_ordering does not check that your __eq__ and __lt__ agree.
sum() of non-numbers needs __radd__ or a start= value.
__exit__ that returns True swallows every exception in the block.
__del__ runs at an unknown time, or never. Clean up with with, not with __del__.
Do not overload an operator with a surprising meaning. A named method is clearer than pipeline + model.