The Python Data Model: Make Your Classes Print, Add and Compare
Vector class for a feature vector. Then print(v) shows a memory address, v + w fails with a TypeError, and Vector(3, 4) == Vector(3, 4) is False. A plain tuple prints its contents, compares by value and can go in a set without being asked.print(x), x + y, x == y, x < y and hash(x) are not special cases in the language. Each one calls a method with a double-underscore name on your object. This lesson builds a small Vector from scratch and adds one such method at the moment the example breaks without it. It comes after the lessons on classes and advanced OOP. The next lesson, Part 2, applies the same idea to len, indexing, loops, calls and with, and the NumPy and pandas lessons after that are about objects built exactly this way.After this lesson, you will be able to:
- Explain how print(x), x + y, x == y and x < y each call a special method on the object's class
- Write __repr__, __add__, __radd__ and __rmul__ so a class prints clearly and works with + and *
- Return NotImplemented, not None, from an operator method that cannot handle its operand
- Define __eq__ and __hash__ together, and keep __lt__ consistent with __eq__
Before you start
#Syntax is a method call
A method whose name starts and ends with two underscores is called a dunder method (short for "double underscore"). You almost never call one yourself. Python calls it when it meets the matching syntax:
| You write | Python calls |
|---|---|
print(x) | x.__str__(), falling back to x.__repr__() |
len(x) | x.__len__() |
x[i] | x.__getitem__(i) |
for item in x | x.__iter__() |
x + y | x.__add__(y) |
x == y | x.__eq__(y) |
item in x | x.__contains__(item) |
f(x) | f.__call__(x) |
with x: | x.__enter__() and x.__exit__(...) |
print, +, == and <. The other rows of the table, len, [], for, f(x) and with, are the subject of Part 2.len() because it has a __len__ method, and you can call it directly to see that.words = ["cat", "dog", "bird"]
print(len(words), words.__len__())
print(words[1], words.__getitem__(1))
print(3 + 4, (3).__add__(4))
print("dog" in words, words.__contains__("dog"))obj.__len__ = lambda: 3 to one instance does nothing for len(obj). The methods belong in the class body.Now the same experiment on a class that has none of these methods. The first two lines give a useless answer and the last one fails.
class Vector:
def __init__(self, *values):
self.values = tuple(values)
v = Vector(3, 4)
w = Vector(1, 2)
print(v) # <__main__.Vector object at 0x...>
print(v == Vector(3, 4)) # False
try:
v + w
except TypeError as err:
print(f"v + w: TypeError: {err}")v + w: TypeError: unsupported operand type(s) for +: 'Vector' and 'Vector'. The message names the capability that is missing. The rest of the lesson supplies such capabilities one at a time. Python never checks what class your object is, only whether it has the method.#Printing: __repr__ and __str__
print(v). __repr__ returns a string for developers. It is what the REPL, logs, error messages and the inside of a list show. The convention is to make it look like the code that would rebuild the object.class Vector:
def __init__(self, *values):
self.values = tuple(values)
def __repr__(self):
return f"Vector{self.values}"
v = Vector(3, 4)
print(v) # Vector(3, 4)
print([v, Vector(1.5, 2)]) # [Vector(3, 4), Vector(1.5, 2)]
print(f"{v} and {v!r}") # Vector(3, 4) and Vector(3, 4)__str__ is the friendlier version that print and str() prefer. You only need it when the end-user text should differ from the debugging text. If a class has __repr__ but no __str__, Python uses __repr__ for both, so write __repr__ first and add __str__ only when you want a second format.A class defines __repr__ returning 'Vector(3, 4)' and no __str__. What does print(v) show?
#Adding vectors: __add__, __radd__, __mul__
v + w. The method receives the right-hand operand as other. If other is not something you know how to handle, return the special value NotImplemented instead of raising an error. That tells Python "I cannot do this, ask the other side". Here is a first attempt with __add__ and __mul__, followed by a surprising result and two lines that still fail.class Vector:
def __init__(self, *values):
self.values = tuple(values)
def __repr__(self):
return f"Vector{self.values}"
def __add__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return Vector(*(a + b for a, b in zip(self.values, other.values)))
def __mul__(self, scalar):
if not isinstance(scalar, (int, float)):
return NotImplemented
return Vector(*(a * scalar for a in self.values))
v, w = Vector(3, 4), Vector(1, 2)
print(v + w) # Vector(4, 6)
print(v * 2) # Vector(6, 8)
print(Vector(1, 2, 3) + Vector(1, 2)) # Vector(2, 4), the third value is dropped
for label, fn in [("2 * v", lambda: 2 * v), ("sum([v, w])", lambda: sum([v, w]))]:
try:
fn()
except TypeError as err:
print(f"{label}: TypeError: {err}")print in the cell. zip stops at the shorter input, so a 3-value vector plus a 2-value vector quietly gives a 2-value vector and the third number is gone. NumPy refuses that mismatch with an error, and a vector class should too. Unequal dimensions are a bug in the caller, not an operand type you cannot handle, so raise ValueError instead of returning NotImplemented. The next version adds that check.2 * v fails because Python asks the left operand first. int.__mul__(2, v) does not know about vectors and returns NotImplemented. Python then tries the reflected method on the right operand, v.__rmul__(2), and your class has none. The same thing happens in sum, which starts from the integer 0 and computes 0 + v. Both are fixed with the reflected methods __rmul__ and __radd__.__abs__ for the length, which abs(v) calls.import math
class Vector:
def __init__(self, *values):
self.values = tuple(values)
def __repr__(self):
return f"Vector{self.values}"
def __add__(self, other):
if not isinstance(other, Vector):
return NotImplemented
if len(self.values) != len(other.values):
raise ValueError(f"dimension mismatch: {len(self.values)} and {len(other.values)}")
return Vector(*(a + b for a, b in zip(self.values, other.values)))
def __radd__(self, other):
if other == 0: # lets sum() start from 0
return self
return NotImplemented
def __mul__(self, scalar):
if not isinstance(scalar, (int, float)):
return NotImplemented
return Vector(*(a * scalar for a in self.values))
__rmul__ = __mul__ # scalar * vector is the same as vector * scalar
def __abs__(self):
return math.hypot(*self.values)
grads = [Vector(1, 2), Vector(3, 4), Vector(5, 6)]
print(sum(grads)) # Vector(9, 12)
print(2 * grads[0]) # Vector(2, 4)
print(abs(Vector(3, 4))) # 5.0
print(sum(grads) * (1 / len(grads))) # Vector(3.0, 4.0)
try:
Vector(1, 2, 3) + Vector(1, 2)
except ValueError as err:
print("ValueError:", err) # ValueError: dimension mismatch: 3 and 2sum(...) * (1 / n) is exactly the shape of code that NumPy arrays and tensors support, and mismatched dimensions raise an error there too, as NumPy does for shapes it cannot broadcast. If you add a vector to something unsupported, such as Vector(1, 2) + 5, both sides return NotImplemented and Python raises the TypeError for you.#Equality and hashing: __eq__ and __hash__
== compares identity, so Vector(3, 4) == Vector(3, 4) is False, as the first experiment showed, and a set would keep both copies. That is the opposite of what you want when you deduplicate feature rows.__eq__ to compare the stored values. Use the same isinstance guard as before so that comparing with an unrelated type answers False. Without the guard, Vector(1, 2) == 3 raises AttributeError when it reaches other.values.class Vector:
def __init__(self, *values):
self.values = tuple(values)
def __repr__(self):
return f"Vector{self.values}"
def __eq__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return self.values == other.values
a, b = Vector(1, 2), Vector(1, 2)
print(a == b) # True
print(a == (1, 2)) # False
print(Vector.__hash__) # None
try:
{a, b}
except TypeError as err:
print("TypeError:", err) # TypeError: unhashable type: 'Vector'__eq__ and does not define __hash__, Python sets __hash__ to None, which makes instances unhashable. They can no longer go in a set or be dict keys.== only on objects in that slot. The old inherited hash was based on identity, so a and b would be equal but would hash differently, and b in {a} could report False. Python removes the hash rather than leave that trap in place. The fix is to define __hash__ from the same fields that __eq__ compares.class Vector:
def __init__(self, *values):
self.values = tuple(values)
def __repr__(self):
return f"Vector{self.values}"
def __eq__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return self.values == other.values
def __hash__(self):
return hash(self.values)
rows = [Vector(1, 2), Vector(3, 4), Vector(1, 2)]
print(len(set(rows))) # 2
counts = {Vector(1, 2): "first row"}
print(counts[Vector(1, 2)]) # first rowvalues is a tuple and nothing reassigns it. A hashable object should not change the fields its hash is built from while it sits in a set or dict, and the mistakes section shows what happens if it does.A class defines __eq__ comparing two fields and nothing else. You build s = {obj1, obj2}. What happens?
#Ordering: __lt__ must agree with __eq__
min and max of them, define __lt__. The decorator functools.total_ordering then fills in <=, > and >= from __eq__ plus that one method. Without it, a <= b raises TypeError even though a < b works.(3, 4) and (5, 0), which both have length 5.import math
from functools import total_ordering
@total_ordering
class Vector:
def __init__(self, *values):
self.values = tuple(values)
def __repr__(self):
return f"Vector{self.values}"
def __eq__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return self.values == other.values
def __hash__(self):
return hash(self.values)
def __abs__(self):
return math.hypot(*self.values)
def __lt__(self, other): # compares length only
if not isinstance(other, Vector):
return NotImplemented
return abs(self) < abs(other)
a, b = Vector(3, 4), Vector(5, 0)
print(a < b, b < a, a == b) # False False False
print(sorted([a, b])) # [Vector(3, 4), Vector(5, 0)]
print(sorted([b, a])) # [Vector(5, 0), Vector(3, 4)]sorted depends on the order you happened to feed it in. Ordering and equality disagree. The fix is to break ties with the values, so that __lt__ calls two vectors equal only when __eq__ does.import math
from functools import total_ordering
@total_ordering
class Vector:
def __init__(self, *values):
self.values = tuple(values)
def __repr__(self):
return f"Vector{self.values}"
def __eq__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return self.values == other.values
def __hash__(self):
return hash(self.values)
def __abs__(self):
return math.hypot(*self.values)
def __lt__(self, other): # length first, then the values break ties
if not isinstance(other, Vector):
return NotImplemented
return (abs(self), self.values) < (abs(other), other.values)
a, b = Vector(3, 4), Vector(5, 0)
print(sorted([a, b])) # [Vector(3, 4), Vector(5, 0)]
print(sorted([b, a])) # [Vector(3, 4), Vector(5, 0)]
print(a <= b, a >= b) # True False(main_key, tie_breaker) is the usual way to make that true.#Common mistakes
#Try it
First, a quick repair. Three feature vectors are being deduplicated with a set, and the line that does it crashes.
Vector compares by value, but building a set of vectors crashes with TypeError. Make the program print 2, the number of distinct vectors.
2
Vector with __repr__, __eq__ and __hash__, and two lines of output. Work through the challenges in order and run after each one.Tests: After the challenges, a + b is Vector(4, 6), sum works on a list of vectors, 2 * a equals a * 2, sorting gives the same order whichever way the input arrives, and the set holds 2 vectors.
#Reference: the dunders in this lesson
| Syntax | Method | Notes |
|---|---|---|
repr(x), REPL, items in a list | __repr__ | Write this first. __str__ falls back to it. |
print(x), str(x), f"{x}" | __str__ | Only when the user-facing text should differ. |
x + y, y + x | __add__, __radd__ | Return NotImplemented for types you do not support. |
x * k, k * x | __mul__, __rmul__ | __rmul__ = __mul__ when the order does not matter. |
abs(x) | __abs__ | |
x == y | __eq__ | Defining it without __hash__ makes the class unhashable. |
hash(x), set members, dict keys | __hash__ | Built from the same fields as __eq__. |
x < y | __lt__ | Keep it consistent with __eq__. total_ordering derives the rest. |
__sub__, __truediv__, __neg__ and __matmul__ for @. NumPy arrays and pandas objects are built from the same methods, which is why a + b on arrays and df["age"] > 21 read like ordinary Python. One difference to remember: == on two NumPy arrays returns an array of booleans, not a single True or False, so if a == b: raises an error for arrays, unlike the Vector.__eq__ written here.#Key Takeaways
Key takeaways
- Built-in syntax such as print(x), x + y, x == y and x < y calls a special method on the object's class, so any class that defines the method works with that syntax.
- Write __repr__ first. Python uses it for print and f-strings too when there is no __str__, and it is what you see inside lists and error messages.
- Return NotImplemented, not None, from an arithmetic or comparison method that cannot handle its operand. Python then tries the other side, and raises TypeError itself if both decline.
- Python asks the left operand first and then the reflected method on the right: __radd__ accepting 0 makes sum() work, and __rmul__ = __mul__ makes 2 * v work.
- Define __eq__ and __hash__ together from the same fields. A class with __eq__ and no __hash__ is unhashable, and an object you mutate while it is in a set or dict key gets lost.
- Keep __lt__ consistent with __eq__ by comparing a tuple that includes a tie-breaker, so sorting does not depend on input order.
A Point class defines __eq__ comparing x and y, and nothing else. What does {Point(1, 2), Point(1, 2)} do?
len, indexing, loops, truthiness, model(x) calls and the rule that gives a method its self.