11 / 22 · Abstraction
The data model
How len, +, ==, for, in, with and a call on an object become calls of special methods on its type; a Vector class built step by step with NotImplemented and reflected operators; descriptors behind properties and methods; abstract base classes against duck typing.
Classes and objects · Iteration, comprehensions and generators
On this page 12
The previous note built classes with attributes and methods. Its plain classes still behave like strangers to the language: they print as <__main__.Account object at 0x…>, compare equal only to themselves, and fail under len, + and for. Built-in types do all of that, and not because the interpreter treats them specially. Every piece of syntax that works on objects, from len(x) to x + y to with, is defined as a call of a method with a double-underscore name, a special method, on the object’s type. The collection of those methods and the rules for calling them is what the language reference calls the data model. This note lists the protocols that matter most, builds a Vector class that supports them one at a time, and ends with the two mechanisms underneath: descriptors, which make properties and methods work, and abstract base classes, which name a protocol.
Conventions. Special methods are often called “dunder” methods, for double underscore: __len__ is “dunder len”. As before, the output is from CPython 3.14.7; addresses such as 0x1082f5e80 differ on every run.
Baseline: a class that Python does not understand#
A vector of numbers, written as a plain class, stores its components and nothing more:
class Vector:
def __init__(self, *components):
self.components = tuple(float(x) for x in components)
>>> v = Vector(3, 4)
>>> v
<__main__.Vector object at 0x1082f5e80>
>>> 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 iterable
The object holds the right data, but every built-in operation either refuses it or does something useless. One could add methods such as v.add(w), v.length() and v.to_string(); then the class would have its own vocabulary that every reader must learn, and functions written for built-in types, such as sum, sorted or print, still would not understand it. The data model lets the class answer the built-in vocabulary instead.
Special methods are looked up on the type#
| You write | Python calls | Protocol |
|---|---|---|
repr(x), the REPL showing x | __repr__ | representation |
str(x), print(x), f"{x}" | __str__ (falls back to __repr__) | representation |
x == y, x != y | __eq__ (and __ne__, derived from it by default) | comparison |
hash(x), x as a dict key or set element | __hash__ | hashing |
len(x) | __len__ | sized |
x[i], x[a:b] | __getitem__ | sequence or mapping |
for item in x, list(x), unpacking | __iter__ (falls back to __getitem__) | iterable |
y in x | __contains__ (falls back to iteration) | container |
if x:, bool(x) | __bool__ (falls back to __len__) | truth |
x + y, x * y, x @ y, -x, abs(x) | __add__, __mul__, __matmul__, __neg__, __abs__ | numeric |
x(...) | __call__ | callable |
with x as y: | __enter__, __exit__ | context manager |
The rule “on the type” can be seen directly. An instance attribute named __len__ is ignored by len:
class Box:
def __len__(self):
return 3
>>> b = Box()
>>> len(b), Box.__len__(b)
(3, 3)
>>> b.__len__ = lambda: 99
>>> len(b), b.__len__()
(3, 99)
b.__len__() is an ordinary attribute lookup, which finds the instance attribute first, as the lookup rule says. len(b) skips the instance and goes straight to the type. The reason is speed and consistency: the interpreter keeps a pointer to each special method in the C structure of the type, so len(b) costs one pointer lookup instead of a dictionary search, and every instance of a type behaves the same way under the same syntax (Python reference, Data model, “Special method lookup”).
Never call special methods directly in ordinary code, such as v.__len__(). Write len(v): the built-in checks the result (__len__ must return a non-negative int), and for operators it runs the full protocol, which a direct call skips, as the section on arithmetic shows.
How an object prints: __repr__ and __str__#
The first step for Vector is to make it readable. Two methods exist because there are two audiences:
__repr__is for the programmer. It should be unambiguous, and where possible it should look like the expression that recreates the object. The REPL, the debugger and containers use it.__str__is for the end user.printand f-strings use it. If a class defines only__repr__,struses that.
datetime.date shows the difference:
>>> import datetime
>>> d = datetime.date(2026, 10, 22)
>>> d
datetime.date(2026, 10, 22)
>>> print(d)
2026-10-22
>>> f"{d}", f"{d!r}"
('2026-10-22', 'datetime.date(2026, 10, 22)')
>>> [d]
[datetime.date(2026, 10, 22)]
A list prints its elements with repr, even inside print, because str of a list is defined as the list’s repr. For Vector, the step is two methods; from here on, each section adds methods to the same class, and the complete class is in the Code section.
import math
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 = Vector(3, 4)
>>> v
Vector(3.0, 4.0)
>>> print(v)
(3, 4)
>>> [v, Vector(1, -2)]
[Vector(3.0, 4.0), Vector(1.0, -2.0)]
The components are stored in a tuple under the name _c, with a leading underscore: the tuple is an internal detail, and the protocols below will be the interface.
Equality and hashing: __eq__ and __hash__#
By default == compares identity: an object equals only itself, which is what object.__eq__ does. A value type, such as 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)
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. Objects that compare equal must have equal hashes: a == b implies hash(a) == hash(b). A dictionary and a set rely on it: they find a key by its hash first and compare with == only inside the bucket that the hash selects, as the dictionaries note explains. The default __hash__ comes from the identity, which agrees with the default __eq__. A class that redefines __eq__ and keeps the identity hash would break the rule, so Python sets __hash__ to None in such a class, which makes its instances unhashable. To be hashable again, the class must define __hash__ from the same data that __eq__ compares, and that data must not change while the object is in a set or a dictionary.
The common mistake: a hash that changes. Here the hash depends on a field that is later modified:
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
False
>>> Key(1) in s
False
>>> Key(2) in s
False
>>> len(s)
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 bucket; Key(1) finds the right bucket but is not equal to the element any more. Hash only what cannot change. That is why lists are unhashable, tuples of hashable items are hashable, and the dataclasses of the previous note need 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)
Returning NotImplemented (a built-in singleton, not an exception) for a foreign type means “I do not know how to compare with that”. Python then tries the other operand’s __eq__, and if that also declines, falls back to identity, so Vector(3, 4) == (3, 4) is False rather than an error. The same value drives the arithmetic protocol below.
Containers: __len__, __getitem__, __iter__, __contains__#
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
([3.0, 4.0], True)
>>> x, y = v
>>> v == Vector(3.0, 4.0), v == (3, 4), {v, Vector(3, 4)}
(True, False, {Vector(3.0, 4.0)})
The rules:
__getitem__receives what is inside the brackets. Forv[0]it is the integer 0; forv[:1]it is asliceobject,slice(None, 1, None). The method above passes integers on to the tuple, which also handles negative indices and raisesIndexErrorout of range, and wraps slices in a newVector, so that slicing a vector gives a vector, as slicing a list gives a list.__iter__returns an iterator. It is the protocol of the iteration note:forcallsiter(v), which callstype(v).__iter__(v), and then callsnexton the result untilStopIteration. Returning the tuple’s own iterator is the simplest correct implementation; writing__iter__as a generator function withyieldis the other common one. Once__iter__exists,list(v), unpackingx, y = v,sum(v),max(v)andzipwork too.inuses__contains__if the class defines it. Otherwise it iterates and compares each item with==; if there is no__iter__either, it calls__getitem__with 0, 1, 2, … untilIndexError. Define__contains__when the class can answer faster than a scan, as a set does with its hash table.- Truth falls back to
__len__. Without__bool__, an object is false when its__len__returns 0, and true otherwise; without either, every object is true. A vector should be false when it is the zero vector, which is not the same as empty, soVectordefines__bool__.
def __abs__(self):
return math.hypot(*self._c)
def __bool__(self):
return any(self._c)
>>> abs(Vector(3, 4)), bool(Vector(0, 0)), bool(Vector(3, 4))
(5.0, False, True)
The old fallback of iteration to __getitem__ is worth knowing because it explains a surprise. A class with only __getitem__ that raises IndexError at the end is iterable:
class Seq:
def __getitem__(self, i):
if i >= 3:
raise IndexError(i)
return i * 10
>>> list(Seq()), 20 in Seq(), 25 in Seq()
([0, 10, 20], True, False)
PyTorch’s Dataset relies on the same two methods: a dataset class defines __len__ and __getitem__, and a DataLoader asks for len(dataset) and indexes it to build batches (the training pipeline).
Arithmetic and NotImplemented#
Vector now supports addition, multiplication by a number on either side, the dot product with @ (the matrix-multiplication operator added by PEP 465 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)
>>> v + w
Vector(4.0, 2.0)
>>> 2 * v, v * 2
(Vector(6.0, 8.0), Vector(6.0, 8.0))
>>> v @ w
-5.0
>>> -w
Vector(-1.0, 2.0)
>>> 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 1
2 * v is the interesting line. The left operand is the integer 2, and int knows nothing about vectors. The binary operators follow a protocol with two chances:
How Python evaluates a binary operator
- The forward method of the left operand.
x * ycallstype(x).__mul__(x, y). If the result is anything butNotImplemented, that is the value of the expression. For2 * v,int.__mul__(2, v)returnsNotImplemented. - The reflected method of the right operand. If the first call returned
NotImplemented, or the method does not exist, and the operands have different types, Python callstype(y).__rmul__(y, x), with the operands swapped. For2 * vthat isVector.__rmul__(v, 2), which returnsVector(6.0, 8.0). TypeError. If both returnNotImplemented, the operation is unsupported. Forv + 1,Vector.__add__(v, 1)declines,int.__radd__(1, v)declines, and Python raises the error in the session above.
There is one refinement: if the right operand’s type is a subclass of the left operand’s type and provides its own reflected method, step 2 runs before step 1, so that a subclass can override an operation of its base in both positions (Python reference, Data model, “Emulating numeric types”).
Why return NotImplemented instead of raising. A method that raises TypeError at once ends the protocol and robs the other operand of its turn. Returning NotImplemented says “not me, ask the other one”. It is what lets a type defined later, such as a NumPy array or your own Vector, cooperate with types written before it, such as int, without either knowing the other. The operator figure makes the order visible; the Code section prints both steps of 2 * v by calling them directly.
The common mistake: sum of objects. sum 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'
>>> sum([v, w], Vector(0, 0))
Vector(4.0, 2.0)
The message names int on the left, which is the clue: give sum a start value of your type, or define __radd__ to accept 0.
Augmented assignment. v += w calls __iadd__ if the class defines it, which may change the object in place. Vector does not define it, so Python falls back to v = v + w: a new object, and the name v is rebound to it. Other names that referred to the old vector still do. For a list, which defines __iadd__, a += [2] changes the list in place, and every name that refers to it sees the change: the names note showed the difference between rebinding and mutating, and here it is the presence or absence of one special method.
Callable objects: __call__#
An instance whose class defines __call__ can be called like a function. It is a function that carries state:
class Scale:
def __init__(self, factor):
self.factor = factor
self.calls = 0
def __call__(self, x):
self.calls += 1
return self.factor * x
>>> double = Scale(2)
>>> double(21), double(5), double.calls
(42, 10, 2)
>>> callable(double), callable(42)
(True, False)
>>> list(map(double, [1, 2, 3]))
[2, 4, 6]
This is the protocol behind every PyTorch model. model(x) calls nn.Module.__call__, which runs any registered hooks and then the forward method you wrote. That is why the documentation asks you to call the module rather than forward directly: a direct call skips the hooks (PyTorch, nn.Module). Functions themselves are objects whose type defines __call__, which the next note builds on.
Context managers: __enter__ and __exit__#
The with statement of the files note is a protocol of two methods. with expr as name: body does the following:
- Evaluate
exprto a context manager objectcm. - Call
type(cm).__enter__(cm)and bind its return value toname. - Run the body.
- However the body ends, normally, with an exception, or with
returnorbreak, calltype(cm).__exit__(cm, exc_type, exc, tb). The three arguments describe the exception, or are allNoneif there was none. - If an exception occurred and
__exit__returned a true value, the exception is suppressed; otherwise it propagates.
A transaction that restores a dictionary when its body fails shows both paths:
class Transaction:
def __init__(self, data):
self.data = data
def __enter__(self):
self.saved = dict(self.data)
return self.data
def __exit__(self, exc_type, exc, tb):
if exc_type is not None:
self.data.clear()
self.data.update(self.saved)
print("rolled back after", exc_type.__name__)
return False
>>> balances = {"ada": 100, "bob": 50}
>>> with Transaction(balances) as b:
... b["ada"] -= 30
... b["bob"] += 30
...
>>> balances
{'ada': 70, 'bob': 80}
>>> with Transaction(balances) as b:
... b["ada"] -= 500
... if b["ada"] < 0:
... raise ValueError("overdrawn")
...
rolled back after ValueError
Traceback (most recent call last):
...
ValueError: overdrawn
>>> balances
{'ada': 70, 'bob': 80}
__exit__ ran in both cases. It returned False, so the ValueError continued to the REPL after the rollback; returning True would have swallowed it, which is rarely what you want. The standard library’s contextlib.contextmanager builds both methods from a generator function, with the code before yield as __enter__ and the code after it as __exit__. torch.no_grad() is a context manager that switches gradient recording off in __enter__ and restores it in __exit__.
Descriptors: what powers properties and methods#
Optional depth: the mechanism under properties, methods and the attribute lookup rule. The rest of the note does not depend on it.
The previous note stated a simple lookup rule (instance first, then the classes in MRO order) and named properties as the exception. Both properties and methods are descriptors: objects stored in a class that define __get__, and possibly __set__ or __delete__. A descriptor with __set__ or __delete__ is a data descriptor; one with only __get__ is a non-data descriptor.
The full rule for reading obj.name, as implemented by object.__getattribute__ (Python reference, Data model, “Invoking descriptors”):
- Search the classes of
type(obj).__mro__forname; call the first matchattr. - If
attris a data descriptor, returnattr.__get__(obj, type(obj)). - Otherwise, if
nameis in the instance’s dictionary, return that value. - Otherwise, if
attris a non-data descriptor, returnattr.__get__(obj, type(obj)). - Otherwise, if
attrwas found, return it as it is. - Otherwise, call the class’s
__getattr__if it has one, or raiseAttributeError.
Assignment obj.name = value calls attr.__set__(obj, value) if attr is a data descriptor, and writes to the instance’s dictionary otherwise.
Functions are non-data descriptors. That one fact explains bound methods:
>>> a = Account(100)
>>> f = Account.__dict__["deposit"]
>>> type(f), hasattr(f, "__get__"), hasattr(f, "__set__")
(<class 'function'>, True, False)
>>> bound = f.__get__(a, Account)
>>> bound
<bound method Account.deposit of <__main__.Account object at 0x10a5c9e80>>
>>> bound(5)
105
>>> a.deposit = "shadowed"
>>> a.deposit
'shadowed'
(Account here is the class of the previous note with only a balance.) a.deposit reaches step 4 and calls the function’s __get__, which returns a bound method, a new one on each access. Because a function is a non-data descriptor, an instance attribute with the same name wins at step 3, as the last two lines show. A property defines __get__ and __set__, so it is a data descriptor and wins at step 2 over anything in the instance dictionary; that is why t.celsius = 100 in the previous note ran the setter instead of storing 100 in t.__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):
if obj is None:
return self
return 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 = width
self.depth = depth
>>> L = Layer(64, 3)
>>> L.width, L.__dict__
(64, {'_width': 64, '_depth': 3})
>>> L.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 name the descriptor was assigned to, so each Positive knows where to store its value. Django model fields, SQLAlchemy columns and functools.cached_property are descriptors. PyTorch’s nn.Module uses the neighbouring hook, __setattr__, which intercepts every assignment to an attribute of the module and records layers and parameters as they are assigned.
Abstract base classes against duck typing#
Python code usually does not check 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 was declared as. The Vector never declared that it is a sequence, yet list(v) and x, y = v work.
Sometimes a program does want to ask “is this a sequence?”, or a library wants to require that a subclass implement certain methods. Abstract base classes (ABCs), in the modules collections.abc and abc, give protocols a name that isinstance understands:
>>> from collections.abc import Iterable, Sized, Sequence, Hashable
>>> v = Vector(3, 4)
>>> isinstance(v, Iterable), isinstance(v, Sized), isinstance(v, Hashable)
(True, True, True)
>>> isinstance(v, Sequence)
False
>>> Sequence.register(Vector)
<class 'vector.Vector'>
>>> isinstance(v, Sequence)
True
(Here Vector was imported from a file vector.py, hence the module name in its repr.) The one-method ABCs, Iterable, Sized, Hashable, Container, recognize any class that defines the method, through a hook called __subclasshook__: they are duck typing made checkable. The richer ABCs, such as Sequence and Mapping, are not inferred from methods, because having __len__ and __getitem__ does not prove that a class means integer indices from 0. A class becomes a Sequence by registering with it, as above, or by inheriting from it. Inheriting brings a reward: a class that defines __len__ and __getitem__ and inherits from Sequence receives __contains__, __iter__, __reversed__, index and count for free:
from collections.abc import Sequence
class Countdown(Sequence):
def __init__(self, n):
self.n = n
def __len__(self):
return self.n
def __getitem__(self, i):
if not 0 <= i < self.n:
raise IndexError(i)
return self.n - i
>>> c = Countdown(4)
>>> list(c), 2 in c, c.index(1), c.count(3), list(reversed(c))
([4, 3, 2, 1], True, 3, 1, [1, 2, 3, 4])
To define an interface of your own, inherit from abc.ABC and mark the required methods with @abstractmethod. The class cannot be instantiated, and neither can a subclass that leaves an abstract method undefined:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self): ...
def describe(self):
return f"{type(self).__name__} with area {self.area():.2f}"
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
class Circle(Shape):
pass
>>> Square(1.5).describe()
'Square with area 2.25'
>>> Circle()
Traceback (most recent call last):
...
TypeError: Can't instantiate abstract class Circle without an implementation for abstract method 'area'
The error appears when the object is created, not when the missing method is first called, which is the point of an ABC. Which to use. Duck typing is the default and keeps code general. ABCs are for frameworks that hand out a base class, and for the few places that must branch on what an object can do. A third option checks protocols without inheritance or registration, before the program runs: typing.Protocol, which the type hints note introduces.
Where the ML courses use the data model#
- NumPy and PyTorch arrays are classes whose special methods do the arithmetic:
a + b,a * b,a @ b,-a,a[1:, ::2]andlen(a)all dispatch to C code.__getitem__there receives tuples and arrays as indices, which is howx[:, 0]and boolean masks work (NumPy arrays). nn.Module.__call__runs hooks and thenforward;Dataset.__len__and__getitem__feed theDataLoader;torch.no_grad()is a context manager (Deep Learning).- pandas uses
__getitem__for column selection (df["price"]), comparison operators that return boolean masks, and__len__for the number of rows (pandas).
What changed#
| Plain class (the baseline) | Class with the data model | |
|---|---|---|
| Printing | <__main__.Vector object at 0x…> | __repr__: Vector(3.0, 4.0); __str__: (3, 4) |
== and hashing | identity | __eq__ by value; __hash__ from the same immutable data |
len, indexing, for, in | TypeError | __len__, __getitem__, __iter__, __contains__ |
+, *, @ | TypeError | forward and reflected methods, NotImplemented to decline |
Calls and with | not possible | __call__; __enter__ and __exit__ |
Works with sum, sorted, zip, print | no | yes, because they are built on the same protocols |
Limitations#
- The note covers the protocols most code needs. The data model also has rich comparisons (
__lt__and the rest, orfunctools.total_ordering),__format__for format specifications,__getattr__and__setattr__for intercepting attribute access,__init_subclass__, the asynchronous protocols (__aiter__,__aenter__), and the buffer and array protocols that NumPy uses. - Special methods implemented in Python cost a Python-level call each time.
Vectoris a teaching example; numerical code uses NumPy arrays, whose special methods run whole loops in C. - The descriptor rule above is
object.__getattribute__. Classes and modules have their own variants, and a class that overrides__getattribute__can do anything.
What you should remember#
- Syntax is a protocol:
len(x),x + y,for,in,with,x()each call a special method ontype(x), never through the instance dictionary. __repr__for programmers,__str__for users; define__repr__first.a == bmust implyhash(a) == hash(b). Defining__eq__makes a class unhashable until it defines__hash__from immutable data.- A binary operator tries
type(x).__op__(x, y), thentype(y).__rop__(y, x), then raisesTypeError. ReturnNotImplementedto decline, never raise. __exit__runs however thewithbody ends; returning a true value suppresses the exception.- Properties and methods are descriptors: data descriptors win over the instance dictionary, non-data descriptors lose to it.
- Duck typing is the default; ABCs name a protocol for
isinstanceand enforce abstract methods at instantiation.
Code#
The script assembles the complete Vector of the note and exercises every protocol: printing, equality and hashing, the sequence protocol, arithmetic with the two steps of 2 * v made explicit, the errors the protocol produces, the lookup of special methods on the type, a set that loses an element whose hash changed, a context manager, a callable object, a descriptor, and the ABC checks. It needs only the standard library; run it with python -I vector.py.
"""The data model: a Vector class that works with Python's syntax, plus the other protocols (Python 3.14)."""
import math
from collections.abc import Iterable, Sequence
class Vector:
def __init__(self, *components):
self._c = tuple(float(x) for x in components)
# how it prints
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) + ")"
# equality and hashing: equal vectors have equal hashes
def __eq__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return self._c == other._c
def __hash__(self):
return hash(self._c)
# the sequence protocol: len, indexing, slicing, iteration
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)
# numeric protocols
def __abs__(self):
return math.hypot(*self._c)
def __bool__(self):
return any(self._c)
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(repr(v), str(v), [v, w])
print(v == Vector(3.0, 4.0), v == (3, 4), len({v, Vector(3, 4), w}))
print(len(v), v[0], v[-1], v[:1], list(v), 4.0 in v)
print(abs(v), bool(Vector(0, 0)), v + w, 2 * v, v @ w, -w)
print(int.__mul__(2, v), Vector.__rmul__(v, 2)) # the two steps behind 2 * v
for expr in ("v + 1", "sum([v, w])", "v + Vector(1, 2, 3)"):
try:
eval(expr)
except (TypeError, ValueError) as err:
print(f"{expr}: {type(err).__name__}: {err}")
print(sum([v, w], Vector(0, 0)))
# special methods are looked up on the type, not on the instance
v.__len__ = lambda: 99
print(len(v), v.__len__())
# a hash that changes after the object is stored: the set loses it
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
print(k in s, Key(1) in s, Key(2) in s, len(s))
# a context manager: __enter__ and __exit__
class Transaction:
def __init__(self, data):
self.data = data
def __enter__(self):
self.saved = dict(self.data)
return self.data
def __exit__(self, exc_type, exc, tb):
if exc_type is not None:
self.data.clear()
self.data.update(self.saved)
print("rolled back after", exc_type.__name__)
return False # do not suppress the exception
balances = {"ada": 100, "bob": 50}
with Transaction(balances) as b:
b["ada"] -= 30
b["bob"] += 30
try:
with Transaction(balances) as b:
b["ada"] -= 500
if b["ada"] < 0:
raise ValueError("overdrawn")
except ValueError as err:
print("caught:", err)
print(balances)
# a callable object: __call__
class Scale:
def __init__(self, factor):
self.factor, self.calls = factor, 0
def __call__(self, x):
self.calls += 1
return self.factor * x
double = Scale(2)
print(list(map(double, [1, 2, 3])), double.calls, callable(double))
# a descriptor: what a property is made of
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()
def __init__(self, width):
self.width = width
layer = Layer(64)
print(layer.width, vars(layer))
try:
layer.width = 0
except ValueError as err:
print("ValueError:", err)
f = Vector.__dict__["__abs__"]
print(type(f).__name__, f.__get__(v, Vector)()) # a function is a descriptor too
# ABCs: Iterable recognizes any class with __iter__; Sequence needs registration
print(isinstance(v, Iterable), isinstance(v, Sequence))
Sequence.register(Vector)
print(isinstance(v, Sequence))
# Output with CPython 3.14.7 on macOS (arm64):
# Vector(3.0, 4.0) (3, 4) [Vector(3.0, 4.0), Vector(1.0, -2.0)]
# True False 2
# 2 3.0 4.0 (3) [3.0, 4.0] True
# 5.0 False (4, 2) (6, 8) -5.0 (-1, 2)
# NotImplemented (6, 8)
# v + 1: TypeError: unsupported operand type(s) for +: 'Vector' and 'int'
# sum([v, w]): TypeError: unsupported operand type(s) for +: 'int' and 'Vector'
# v + Vector(1, 2, 3): ValueError: zip() argument 2 is longer than argument 1
# (4, 2)
# 2 99
# False False False 1
# rolled back after ValueError
# caught: overdrawn
# {'ada': 70, 'bob': 80}
# [2, 4, 6] 3 True
# 64 {'_width': 64}
# ValueError: width must be positive, got 0
# function 5.0
# True False
# True
print with several arguments converts each with str, which is why vectors appear as (4, 2) in most lines and as Vector(...) only inside the list of the first line. The set {v, Vector(3, 4), w} has 2 elements because the first two are equal and have equal hashes.
Next#
Scale was an object that behaves like a function and remembers its factor. Python’s own functions are objects too, and a function defined inside another function can remember the variables around it without any class. The next note shows how such closures store those variables, the trap they set in loops, and the decorators built on them, from functools.cache to @torch.no_grad().
References#
- Python documentation (3.14): Data model, sections “Basic customization” (
__repr__,__str__,__eq__,__hash__), “Invoking descriptors”, “Emulating container types”, “Emulating numeric types”, “With statement context managers” and “Special method lookup”; Thewithstatement; Descriptor Guide;collections.abc;abc;contextlib. - N. J. Smith. PEP 465 — A dedicated infix operator for matrix multiplication. 2014.
- G. van Rossum, T. Wouters. PEP 343 — The “with” Statement. 2005.
- G. van Rossum, T. Wouters. PEP 3119 — Introducing Abstract Base Classes. 2007.
- L. Ramalho. Fluent Python, 2nd ed. O’Reilly, 2022. Ch. 1 (the Python data model), ch. 11 and 12 (a Pythonic object, special methods for sequences, the
Vectorexample), ch. 13 (interfaces, protocols and ABCs), ch. 16 (operator overloading), ch. 23 (attribute descriptors). - PyTorch documentation.
torch.nn.Module(forwardand__call__),torch.utils.data(map-style datasets),torch.no_grad.