The data model
How len, ==, +, for, in, with and calls become special methods on the type: a Vector class built step by step, equality and hashing, NotImplemented and reflected operators, descriptors behind properties and methods, ABCs against duck typing.
A class Python does not understand
The topic Classes and objects gave our own types attributes, methods and inheritance, and a dataclass gave Config a readable printout and comparison by value without a line of our code. A plain class gets neither. Here is a vector of numbers written as a plain class:
class Vector:
def __init__(self, *components):
self.components = tuple(float(x) for x in components)It holds the right data, and the language still treats it as a stranger. The address after 0x changes from run to run.
>>> v = Vector(3, 4)
>>> v
<__main__.Vector object at 0x...>
>>> v == Vector(3, 4)
False
>>> len(v)
Traceback (most recent call last):
...
TypeError: object of type 'Vector' has no len()
>>> v + v
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +: 'Vector' and 'Vector'
>>> for x in v: pass
...
Traceback (most recent call last):
...
TypeError: 'Vector' object is not iterableBuilt-in types do all of this, and not because the interpreter treats them specially. Every piece of syntax that works on objects is defined as a call of a method with a double-underscore name, a special method (a "dunder" method), on the object's type:
| You write | Python calls |
|---|---|
repr(x), str(x), print(x) |
__repr__, __str__ |
x == y, hash(x) |
__eq__, __hash__ |
len(x), x[i], for, y in x, if x: |
__len__, __getitem__, __iter__, __contains__, __bool__ |
x + y, x * y, x @ y, -x, abs(x) |
__add__, __mul__, __matmul__, __neg__, __abs__ |
x(...), with x: |
__call__, __enter__ and __exit__ |
These methods and the rules for calling them make up the data model. A class that defines them speaks the language's own vocabulary, and so does every function built on it: print, sum, sorted, zip. This topic teaches Vector that vocabulary one group at a time.
"On the type" is meant literally. len(x) is type(x).__len__(x), and an instance attribute with the same name is ignored:
class Box:
def __len__(self):
return 3>>> b = Box()
>>> b.__len__ = lambda: 99
>>> len(b), b.__len__()
(3, 99)b.__len__() is an ordinary attribute lookup, and it finds the instance attribute first. len(b) goes straight to the type. CPython keeps a pointer to each special method in the type's C structure: one pointer instead of a dictionary search, and every instance of a type behaves the same. So write len(v), never v.__len__(). The built-in also checks the result, and for operators it runs the full protocol that a direct call skips.
How an object prints
The first step is to make a vector readable. There are two methods because there are two audiences.
__repr__is for the programmer. It is unambiguous and, where possible, looks like the expression that recreates the object. The REPL, the debugger and containers use it.__str__is for the end user.print,strand f-strings use it. If a class defines only__repr__,strfalls back to it.
From here on the components live in a tuple _c. The leading underscore marks it as an internal detail: the protocols will be the interface. Every later block adds methods to this same class.
class Vector:
def __init__(self, *components):
self._c = tuple(float(x) for x in components)
def __repr__(self):
return f"Vector({', '.join(repr(x) for x in self._c)})"
def __str__(self):
return "(" + ", ".join(f"{x:g}" for x in self._c) + ")">>> v, w = Vector(3, 4), Vector(1, -2.5)
>>> v
Vector(3.0, 4.0)
>>> print(v)
(3, 4)
>>> f"{v}", f"{v!r}"
('(3, 4)', 'Vector(3.0, 4.0)')
>>> print([v, w])
[Vector(3.0, 4.0), Vector(1.0, -2.5)]The format spec g drops the trailing .0, and !r inside an f-string asks for repr. The last line is the one to remember: a list shows its elements with repr, even inside print. The str of a list is its repr, and that calls repr on every element.
Equality and hashing
By default == compares identity: an object equals only itself. A vector should compare by value. Defining __eq__ has a consequence that surprises many people:
class P:
def __init__(self, x):
self.x = x
def __eq__(self, other):
return isinstance(other, P) and self.x == other.x>>> P(1) == P(1), P(1) != P(2)
(True, True)
>>> P.__hash__ is None
True
>>> {P(1)}
Traceback (most recent call last):
...
TypeError: cannot use 'P' as a set element (unhashable type: 'P')The rule behind it: objects that compare equal must have equal hashes. If a == b, then hash(a) == hash(b). The topic Dictionaries and sets showed why. A dict or a set finds a key by its hash first, and compares with == only against the entries that hash leads to. The default hash comes from identity, which agrees with the default ==. A class that redefines __eq__ and kept the identity hash would break the rule, so Python sets its __hash__ to None. != needs nothing extra: by default it inverts __eq__.
To become hashable again, a class defines __hash__ from the same data that __eq__ compares. That data must not change while the object sits in a set or a dict. Here is what happens when it does:
class Key:
def __init__(self, x):
self.x = x
def __eq__(self, other):
return isinstance(other, Key) and self.x == other.x
def __hash__(self):
return hash(self.x)>>> k = Key(1)
>>> s = {k}
>>> k.x = 2
>>> k in s, Key(1) in s, Key(2) in s, len(s)
(False, False, False, 1)The set still holds one element and can no longer find it by any key. k in s hashes the new value 2 and looks in the wrong place. Key(1) looks in the right place, but the element there is no longer equal to it. Hash only what cannot change. That is why lists are unhashable and a dataclass needs frozen=True to get a hash.
Vector keeps its components in an immutable tuple, so it can be hashable:
def __eq__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return self._c == other._c
def __hash__(self):
return hash(self._c)>>> v = Vector(3, 4)
>>> v == Vector(3.0, 4.0), v == (3, 4), hash(v) == hash(Vector(3, 4))
(True, False, True)
>>> {v: "train"}[Vector(3, 4)]
'train'NotImplemented is a built-in constant, not an exception. Returning it means "I cannot compare with that". Python then asks the other operand, and if it declines too, == falls back to identity. So a vector compared with a tuple gives False instead of an error. Arithmetic operators, two blocks on, use the same signal.
A vector as a sequence
Three methods make Vector a sequence of numbers:
def __len__(self):
return len(self._c)
def __getitem__(self, index):
if isinstance(index, slice):
return Vector(*self._c[index])
return self._c[index]
def __iter__(self):
return iter(self._c)>>> v = Vector(3, 4)
>>> len(v), v[0], v[-1], v[:1]
(2, 3.0, 4.0, Vector(3.0))
>>> list(v), 4.0 in v, max(v)
([3.0, 4.0], True, 4.0)
>>> x, y = v
>>> x, y
(3.0, 4.0)__getitem__receives what is inside the brackets. Forv[0]it is the integer 0, forv[:1]asliceobject. The tuple handles negative indices and raisesIndexErrorout of range. Slices are wrapped in a newVector, so a slice of a vector is a vector, as a slice of a list is a list.__iter__returns an iterator, the protocol from the topic Iteration, comprehensions and generators. Handing out the tuple's own iterator is the simplest correct choice; a generator function withyieldis the other common one. Once it exists,list, unpacking,sum,maxandzipwork too.incalls__contains__if the class has one. Otherwise it iterates and compares each item with==. With no__iter__either, it calls__getitem__with 0, 1, 2, … untilIndexError.- Truth falls back to
__len__. Without__bool__, an object is false when its length is 0. Without both methods, every object is true.
A vector should be false when it is the zero vector, which is not the same as empty. So Vector defines __bool__, and __abs__ for its length (with import math at the top of the file):
def __abs__(self):
return math.hypot(*self._c)
def __bool__(self):
return any(self._c)>>> abs(v), bool(Vector(0, 0)), bool(v)
(5.0, False, True)The old fallback to __getitem__ explains a surprise: a class with nothing but __getitem__ is iterable.
class Seq:
def __getitem__(self, i):
if i >= 3:
raise IndexError(i)
return i * 10>>> list(Seq()), 20 in Seq()
([0, 10, 20], True)PyTorch's Dataset relies on the same pair of methods. A dataset class defines __len__ and __getitem__, and a DataLoader asks for len(dataset) and indexes it to build batches.
Operators and NotImplemented
Vector now gets addition, multiplication by a number on either side, the dot product with @ (the matrix-multiplication operator, added to Python for NumPy) and negation:
def __add__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return Vector(*(a + b for a, b in zip(self, other, strict=True)))
def __mul__(self, k):
if not isinstance(k, (int, float)):
return NotImplemented
return Vector(*(k * x for x in self))
def __rmul__(self, k):
return self * k def __matmul__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return sum(a * b for a, b in zip(self, other, strict=True))
def __neg__(self):
return -1 * self>>> v, w = Vector(3, 4), Vector(1, -2)
>>> print(v + w, 2 * v, v * 2, v @ w, -w)
(4, 2) (6, 8) (6, 8) -5.0 (-1, 2)
>>> v + 1
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +: 'Vector' and 'int'
>>> v + Vector(1, 2, 3)
Traceback (most recent call last):
...
ValueError: zip() argument 2 is longer than argument 1A binary operator such as x * y gives both operands a chance:
- The forward method of the left operand. Python calls
type(x).__mul__(x, y). Any result exceptNotImplementedis the value of the expression. - The reflected method of the right operand. If the first call returned
NotImplemented, or the method is missing, and the types differ, Python callstype(y).__rmul__(y, x)with the operands swapped. TypeError. If both decline, the operation is unsupported. Forv + 1, bothVector.__add__andint.__radd__returnNotImplemented.
One refinement: if the right operand's type is a subclass of the left one's and overrides the reflected method, step 2 goes first. That lets a subclass override its base in both positions.
Why return NotImplemented instead of raising TypeError? Raising ends the protocol at once and robs the other operand of its turn. NotImplemented says "not me, ask the other one". That is how a type written later, such as a NumPy array or our Vector, cooperates with a type written earlier, such as int, with neither knowing about the other.
sum shows the protocol at work. It starts from the integer 0, so its first step is 0 + v:
>>> sum([v, w])
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +: 'int' and 'Vector'
>>> print(sum([v, w], Vector(0, 0)))
(4, 2)Augmented assignment. v += w calls __iadd__ if the class has one, and that method may change the object in place. Vector has none, so Python falls back to v = v + w: a new object, and only the name v is rebound. A list does define __iadd__, so a += [3] changes the list itself. This is the difference between rebinding and mutation from the topic Values, types and names, decided by one special method.
Calls and with
An instance whose class defines __call__ can be called like a function. It is a function that carries state. Here it keeps a running mean of the losses a training loop reports:
class RunningMean:
def __init__(self):
self.total, self.count = 0.0, 0
def __call__(self, loss):
self.total += loss
self.count += 1
return self.total / self.count>>> mean = RunningMean()
>>> mean(1.0), mean(0.5), mean(0.0)
(1.0, 0.75, 0.5)
>>> mean.count, callable(mean), callable(0.5)
(3, True, False)This is the protocol behind every PyTorch model. model(x) calls nn.Module.__call__, which runs the registered hooks and then the forward method you wrote. That is why the documentation says to call the module rather than forward.
The with statement from the topic Files and exceptions is a protocol of two methods. with expr as name: body runs like this:
- Evaluate
exprto a context managercm. - Call
type(cm).__enter__(cm)and bind its result toname. - Run the body.
- However the body ends (normally, with an exception, with
returnorbreak), calltype(cm).__exit__(cm, exc_type, exc, tb). The three arguments describe the exception, or are allNone. - If there was an exception and
__exit__returned a true value, the exception is suppressed. Otherwise it propagates.
Here is a manager that switches a model into evaluation mode and always switches it back:
class Model:
training = True
class EvalMode:
def __init__(self, model):
self.model = model
def __enter__(self):
self.saved = self.model.training
self.model.training = False
return self.model
def __exit__(self, exc_type, exc, tb):
self.model.training = self.saved
return False>>> net = Model()
>>> with EvalMode(net) as m:
... print(m.training)
...
False
>>> with EvalMode(net):
... raise ValueError("bad batch")
...
Traceback (most recent call last):
...
ValueError: bad batch
>>> net.training
True__exit__ ran both times and restored the flag. It returned False, so the ValueError still reached the REPL. The standard library's contextlib.contextmanager builds both methods from a generator function: the code before yield becomes __enter__, the code after it __exit__. torch.no_grad() is a context manager too: it switches gradient recording off on entry and restores it on exit.
Descriptors under properties and methods
The topic Classes and objects gave a simple lookup rule for obj.name: the instance first, then the classes along the MRO. A property did not fit it: assigning to a property ran its setter instead of writing to the instance. Properties and methods both run on one mechanism, the descriptor.
A descriptor is an object stored in a class that defines __get__, and possibly __set__ or __delete__. With __set__ or __delete__ it is a data descriptor; with only __get__ it is a non-data descriptor. The full rule for reading obj.name, as object.__getattribute__ implements it:
- Find
namein the classes oftype(obj).__mro__and call the first matchattr. - If
attris a data descriptor, returnattr.__get__(obj, type(obj)). - Otherwise, if
nameis in the instance's__dict__, return that value. - Otherwise, if
attris a non-data descriptor, returnattr.__get__(obj, type(obj)). - Otherwise return
attritself if step 1 found it. Failing that, call the class's__getattr__if it has one, or raiseAttributeError.
Assigning obj.name = value calls attr.__set__(obj, value) for a data descriptor and writes to the instance's __dict__ otherwise. A function is a non-data descriptor, and that explains bound methods:
>>> v = Vector(3, 4)
>>> f = Vector.__dict__["__abs__"]
>>> type(f).__name__, hasattr(f, "__get__"), hasattr(f, "__set__")
('function', True, False)
>>> f.__get__(v, Vector)
<bound method Vector.__abs__ of Vector(3.0, 4.0)>
>>> v.__abs__ = lambda: "shadowed"
>>> v.__abs__(), abs(v)
('shadowed', 5.0)
>>> hasattr(property, "__get__"), hasattr(property, "__set__")
(True, True)Reading a method reaches step 4, and the function's __get__ returns a bound method. An instance attribute wins at step 3, so the lambda shadows the method for an ordinary lookup, while abs(v) still goes to the type, as in the first block. A property has both __get__ and __set__. It is a data descriptor and wins at step 2 over anything in the instance's __dict__.
A descriptor of your own is a reusable property. This one validates a field in any class that uses it:
class Positive:
def __set_name__(self, owner, name):
self.name = "_" + name
def __get__(self, obj, objtype=None):
return self if obj is None else getattr(obj, self.name)
def __set__(self, obj, value):
if value <= 0:
raise ValueError(f"{self.name[1:]} must be positive, got {value}")
setattr(obj, self.name, value)
class Layer:
width = Positive()
depth = Positive()
def __init__(self, width, depth):
self.width, self.depth = width, depth>>> layer = Layer(64, 3)
>>> layer.width, vars(layer)
(64, {'_width': 64, '_depth': 3})
>>> layer.depth = 0
Traceback (most recent call last):
...
ValueError: depth must be positive, got 0__set_name__ is called once, when the class body ends, with the attribute's name, so each Positive knows where to keep its value. functools.cached_property, Django model fields and SQLAlchemy columns are descriptors too.
ABCs and duck typing
Python code rarely checks types. A function that loops over its argument works with anything that has __iter__ and fails with a clear error otherwise. This is duck typing: an object is judged by the methods it has, not by the class it declares. Vector never said it was a sequence, yet list(v) and x, y = v work.
Sometimes a program does want to ask "can I iterate over this?", or a library wants to require that subclasses implement certain methods. Abstract base classes (ABCs) from collections.abc and abc give a protocol a name that isinstance understands:
>>> from collections.abc import Iterable, Sized, Hashable, Sequence
>>> v = Vector(3, 4)
>>> isinstance(v, Iterable), isinstance(v, Sized), isinstance(v, Hashable)
(True, True, True)
>>> isinstance(v, Sequence)
False
>>> Sequence.register(Vector)
<class '__main__.Vector'>
>>> isinstance(v, Sequence)
TrueThe one-method ABCs, such as Iterable, Sized, Hashable and Container, recognize any class that defines their method: duck typing made checkable. Richer ABCs such as Sequence are not inferred, because __len__ and __getitem__ do not prove that a class means integer indices from 0. A class becomes a Sequence by registering, as above, or by inheriting from it. Inheriting pays: from __len__ and __getitem__ alone, the class gets __contains__, __iter__, __reversed__, index and count for free.
To define an interface of your own, inherit from abc.ABC and mark the required methods with @abstractmethod:
from abc import ABC, abstractmethod
class Metric(ABC):
@abstractmethod
def compute(self, y_true, y_pred): ...
def report(self, y_true, y_pred):
return f"{type(self).__name__}: {self.compute(y_true, y_pred):.3f}"
class Accuracy(Metric):
def compute(self, y_true, y_pred):
return sum(t == p for t, p in zip(y_true, y_pred)) / len(y_true)
class F1(Metric):
pass>>> Accuracy().report([1, 0, 1], [1, 1, 1])
'Accuracy: 0.667'
>>> F1()
Traceback (most recent call last):
...
TypeError: Can't instantiate abstract class F1 without an implementation for abstract method 'compute'The error comes when the object is created, not when the missing method is first called: that is the point of an ABC. Duck typing stays the default. ABCs are for frameworks that hand out a base class and for the rare code that must branch on what an object can do. The topic Type hints adds a third way, typing.Protocol, which is checked before the program runs.
RunningMean was an object that behaves like a function and remembers its state between calls. Python's own functions are objects too, and their type defines __call__. A function defined inside another function can remember the variables around it with no class at all. The topic Closures and decorators shows how such closures keep those variables, the trap they set in loops, and the decorators built on top of them.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.