Sub topic 6
Making objects feel built-in with special methods
This chapter assumes you can write a class with __init__ and instance methods, and that you know the difference between instance and class attributes. You do not need inheritance yet. You do need to be comfortable reading short Python scripts and running them in a REPL.
What special methods are
A special method (also called a dunder method, from "double underscore") is a method with a reserved name such as __repr__ or __add__. You rarely call these methods yourself. Python calls them when you use certain syntax or built-in functions:
| You write | Python calls |
|---|---|
| `repr(x)`, or `x` in the REPL | `type(x).__repr__(x)` |
| `str(x)`, `print(x)` | `type(x).__str__(x)` |
| `x == y` | `type(x).__eq__(x, y)` |
| `x + y` | `type(x).__add__(x, y)` |
| `len(x)` | `type(x).__len__(x)` |
| `x[i]` | `type(x).__getitem__(x, i)` |
| `bool(x)`, `if x:` | `__bool__`, or else `__len__` |
| `hash(x)` | `type(x).__hash__(x)` |
Python looks these methods up on the type, not on the instance. Assigning obj.__len__ = lambda: 3 on one object does not make len(obj) work.
Readable output with `__repr__` and `__str__`
__repr__ should return an unambiguous string for developers, ideally one that looks like the code that would rebuild the object. __str__ returns a friendly string for end users. If you define only __repr__, str() and print() fall back to it, so __repr__ is the one to write first.
Inside an f-string, !r applies repr() to a value. That is why the Vector below prints strings with quotes and numbers without them.
import math
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Vector({self.x!r}, {self.y!r})"
def __eq__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))
def __add__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return Vector(self.x + other.x, self.y + other.y)
def __mul__(self, scalar):
if not isinstance(scalar, (int, float)):
return NotImplemented
return Vector(self.x * scalar, self.y * scalar)
__rmul__ = __mul__
def __abs__(self):
return math.hypot(self.x, self.y)
def __bool__(self):
return bool(self.x or self.y)
v = Vector(1, 2)
print(v + Vector(3, 4)) # Vector(4, 6)
print(v * 3) # Vector(3, 6)
print(3 * v) # Vector(3, 6)
print(abs(Vector(3, 4))) # 5.0
print(bool(Vector(0, 0))) # False
print(len({Vector(1, 2), Vector(1, 2)})) # 1The rest of this chapter explains why each piece is written the way it is.
Equality and hashing go together
By default, == compares identity, so two separate Vector(1, 2) objects are not equal. Defining __eq__ changes that to value comparison.
Defining __eq__ has a side effect. Python sets __hash__ to None on any class that defines __eq__ without defining __hash__. Instances then become unhashable, and you get TypeError: unhashable type when you put them in a set or use them as dict keys. The rule behind this is that objects that compare equal must have equal hashes.
The Vector above defines both. It hashes the same tuple it compares, which keeps the rule intact.
Returning `NotImplemented`
Look at how __eq__ and __add__ handle a value of the wrong type. They return NotImplemented, which is a special constant and not an exception. It tells Python that this class does not know how to handle that operand, so Python should try the other side.
For a + b, Python first calls a.__add__(b). If that returns NotImplemented, Python calls the reflected method b.__radd__(a). If that also returns NotImplemented or does not exist, Python raises TypeError.
This is why 3 * v works. int.__mul__(3, v) returns NotImplemented, so Python tries v.__rmul__(3). The line __rmul__ = __mul__ reuses the same method, which is correct here because scalar multiplication is commutative.
If you raise TypeError yourself inside __add__, the reflected method never gets a chance. Return NotImplemented instead.
The same protocol applies to ==. If both sides return NotImplemented, Python falls back to identity comparison, so Vector(1, 2) == "text" is False and does not raise.
Ordering and `total_ordering`
Sorting and the <, <=, >, >= operators use __lt__, __le__, __gt__, and __ge__. Writing all four is repetitive. The functools.total_ordering decorator fills in the rest if you provide __eq__ and one ordering method.
from functools import total_ordering
@total_ordering
class Version:
def __init__(self, text):
self.parts = tuple(int(p) for p in text.split("."))
def __repr__(self):
return f"Version({str(self)!r})"
def __str__(self):
return ".".join(str(p) for p in self.parts)
def __eq__(self, other):
if not isinstance(other, Version):
return NotImplemented
return self.parts == other.parts
def __lt__(self, other):
if not isinstance(other, Version):
return NotImplemented
return self.parts < other.parts
versions = [Version("1.10"), Version("1.2"), Version("1.9")]
print(sorted(versions)) # [Version('1.2'), Version('1.9'), Version('1.10')]
print(Version("1.10") > Version("1.9")) # True
print(max(versions)) # 1.10
print(Version("1.2") <= Version("1.2")) # True
try:
Version("1.0") < 3
except TypeError as exc:
print("TypeError:", exc)The version parts are compared as integer tuples, so 1.10 correctly sorts after 1.9. A plain string comparison would get that wrong. Printing max(versions) uses __str__, while the list display uses __repr__.
The decorator adds some call overhead to the derived methods. If sorting speed matters in a hot path, write the methods by hand.
Truthiness and containers
if obj: calls __bool__. If the class has no __bool__, Python calls __len__ and treats 0 as false. If neither exists, the object is always true.
A few methods are enough to make a class behave like a sequence:
class Playlist:
def __init__(self, songs):
self._songs = list(songs)
def __len__(self):
return len(self._songs)
def __getitem__(self, index):
return self._songs[index]
p = Playlist(["intro", "verse", "outro"])
print(len(p)) # 3
print(p[0], p[-1]) # intro outro
print(p[0:2]) # ['intro', 'verse']
for song in p:
print(song) # intro, verse, outro on separate lines
print("verse" in p) # True
print(list(reversed(p))) # ['outro', 'verse', 'intro']
print(bool(Playlist([]))) # FalseOnly __len__ and __getitem__ are defined, yet iteration, in, and reversed() all work. Python falls back to calling __getitem__ with 0, 1, 2, ... until it gets an IndexError, and reversed() uses __len__ and __getitem__ together. For explicit control, define __iter__ (which returns an iterator) and __contains__. Define them whenever lookup can be faster than a linear scan.
Here p[0:2] returns a plain list because the slice is passed straight to the underlying list. If you want a slice to return a Playlist, check isinstance(index, slice) and wrap the result.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `unhashable type: 'Vector'` | Defined `__eq__` without `__hash__` | Add `__hash__` over the compared fields, or keep the class unhashable on purpose |
| `TypeError: unsupported operand type(s) for +` | `__add__` returned `NotImplemented` and no `__radd__` exists | Implement the reflected method, or pass a supported type |
| `sum(vectors)` fails | `sum` starts with `0`, and `0 + Vector` has no matching method | Call `sum(vectors, Vector(0, 0))` |
| `<=` raises `TypeError` | Only `__lt__` defined | Add `@total_ordering`, or define the other methods |
| `print(obj)` shows `<__main__.X object at 0x...>` | No `__repr__` or `__str__` | Add `__repr__` |
| A mutated key vanishes from a dict | Hash depends on a field that changed | Make the hashed fields immutable |
Exercise
A class defines __eq__ comparing self.name, but nothing else. A colleague adds instances to a set and gets TypeError: unhashable type. Give two valid fixes and say when each is appropriate.
Show answer
Fix 1: add def __hash__(self): return hash(self.name), which is appropriate when name never changes after creation, so equal objects keep equal hashes. Fix 2: leave the class unhashable and use a list or key the set by obj.name instead, which is appropriate when the object is mutable and its identity for comparison can change.
Exercise
Money defines __add__ that accepts only another Money, and Money(5) + 3 raises a TypeError from inside __add__. A teammate wants 3 + Money(5) to work too. Why will adding __radd__ not help while __add__ raises, and what should the check return instead?
Show answer
3 + Money(5) calls int.__add__(3, Money(5)), which returns NotImplemented, so Python then calls Money.__radd__. That part works once __radd__ exists. The problem arises in the opposite order, Money(5) + obj: raising TypeError inside __add__ stops Python before it can try obj.__radd__. The method should return NotImplemented for unsupported operands and let Python decide whether to try the reflected method or raise TypeError.