Python Operator Overloading and Comparison
What you will learn
- How operators map to special methods
- Writing
__add__,__mul__,__neg__,__abs__and returningNotImplemented - Reflected operators (
__radd__,__rmul__) and howsumuses them __eq__and its link to__hash__- Ordering with
__lt__andfunctools.total_ordering - In-place operators such as
+=
1. Operators are method calls
When you write a + b, Python really calls a.__add__(b). For numbers and strings, those methods are built in. For your own classes, you can define them, and +, ==, < and the others will work on your objects. This is called operator overloading.
| Operator | Method | Operator | Method | |
|---|---|---|---|---|
a + b |
__add__ |
a == b |
__eq__ |
|
a - b |
__sub__ |
a != b |
__ne__ |
|
a * b |
__mul__ |
a < b |
__lt__ |
|
a / b |
__truediv__ |
a <= b |
__le__ |
|
a // b |
__floordiv__ |
a > b |
__gt__ |
|
a % b |
__mod__ |
a >= b |
__ge__ |
|
a ** b |
__pow__ |
-a |
__neg__ |
|
a @ b |
__matmul__ |
abs(a) |
__abs__ |
Use it only when the meaning is natural: adding two vectors, comparing two money amounts. Do not make + do something surprising.
Quick check: what does Python call for `a - b`?
a.__sub__(b).
2. A class with arithmetic: Vec
Here is a two-dimensional vector (a pair of numbers) with several operators:
class Vec:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f"Vec({self.x}, {self.y})"
def __add__(self, other):
if not isinstance(other, Vec):
return NotImplemented
return Vec(self.x + other.x, self.y + other.y)
def __sub__(self, other):
if not isinstance(other, Vec):
return NotImplemented
return Vec(self.x - other.x, self.y - other.y)
def __mul__(self, k):
if not isinstance(k, (int, float)):
return NotImplemented
return Vec(self.x * k, self.y * k)
__rmul__ = __mul__
def __neg__(self):
return Vec(-self.x, -self.y)
def __abs__(self):
return (self.x ** 2 + self.y ** 2) ** 0.5
a = Vec(1, 2)
b = Vec(3, 4)
print(a + b)
print(b - a)
print(a * 3)
print(3 * a)
print(-a)
print(abs(b))
Vec(4, 6)
Vec(2, 2)
Vec(3, 6)
Vec(3, 6)
Vec(-1, -2)
5.0
Key points:
- Each operator method returns a new object and leaves the operands unchanged, like
+on numbers. __neg__and__abs__are the one-operand methods (-aandabs(a)).__rmul__ = __mul__is explained in section 4.
3. NotImplemented
If your method does not know how to handle the other operand, it should return NotImplemented (not raise an error, and not return None). That tells Python: "I cannot do this one; try something else." Python then tries the other object's reflected method, and only if that also fails, raises the proper TypeError:
a + 1
TypeError: unsupported operand type(s) for +: 'Vec' and 'int'
Here Vec.__add__ returned NotImplemented, int could not add a Vec either, so Python reported a clear TypeError. If you had written return None, the code would continue silently with None as the result.
NotImplemented is not an exception: it is a special value that you return. (It is also not NotImplementedError, which you raise, lesson 13.5.)
4. Reflected operators: radd and rmul
3 * a has the number first. Python tries int.__mul__(3, a), which does not know a Vec, and returns NotImplemented. Then Python tries the reflected method on the right-hand object: a.__rmul__(3). That is why __rmul__ = __mul__ lets 3 * a work. Each operator has a reflected twin with an r in the name:
| Operator | Normal | Reflected (when the left operand cannot do it) |
|---|---|---|
a + b |
a.__add__(b) |
b.__radd__(a) |
a * b |
a.__mul__(b) |
b.__rmul__(a) |
a - b |
a.__sub__(b) |
b.__rsub__(a) |
The built-in sum starts from 0 and adds items with +, so 0 + money needs __radd__. Without it, sum of your objects fails unless you give a start value:
print(sum([Vec(1, 2), Vec(3, 4)], Vec(0, 0)))
Vec(4, 6)
The start value Vec(0, 0) replaced the default 0. Or define __radd__ so 0 + obj works (the Money class below does).
5. Equality: eq and hash
By default, == compares identity: two objects are equal only if they are the same object (lesson 13.1):
class P:
def __init__(self, x):
self.x = x
print(P(1) == P(1))
False
To compare by value, define __eq__. It should also return NotImplemented (or False) for objects of other types:
class Vec2(Vec):
def __eq__(self, other):
return isinstance(other, Vec) and (self.x, self.y) == (other.x, other.y)
print(Vec2(1, 2) == Vec2(1, 2), Vec2(1, 2) != Vec2(3, 4))
print(Vec2(1, 2) == (1, 2))
True True
False
!=works automatically: Python uses the opposite of__eq__.- Comparing with a tuple is
False, because of theisinstancecheck.
The hash rule
If you define __eq__, Python removes the default __hash__, making the class unhashable (lesson 9.7):
class E:
def __init__(self, x):
self.x = x
def __eq__(self, other):
return self.x == other.x
hash(E(1))
TypeError: unhashable type: 'E'
So E cannot be a dictionary key or a set member. If objects that are equal should be usable as keys, define __hash__ as well, built from the same data, and the data must not change while the object is in a dictionary or set:
class Vec3(Vec):
def __eq__(self, other):
return isinstance(other, Vec) and (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))
d = {Vec3(1, 2): "a"}
print(d[Vec3(1, 2)], Vec3(1, 2) in d, len({Vec3(1, 2), Vec3(1, 2)}))
a True 1
Rule of thumb: equal objects must have equal hashes. For a class that can change, leave it unhashable. Lesson 13.11's frozen dataclass does all this for you.
6. Ordering: lt and total_ordering
For <, >, <=, >= you need the ordering methods. And you get sorted, min and max for free (lessons 7.4 and 9.6). In practice, sorted and max need only __lt__:
class Ver:
def __init__(self, major, minor):
self.major, self.minor = major, minor
def _key(self):
return (self.major, self.minor)
def __eq__(self, other):
return isinstance(other, Ver) and self._key() == other._key()
def __lt__(self, other):
return self._key() < other._key()
def __repr__(self):
return f"Ver({self.major}.{self.minor})"
v1, v2, v3 = Ver(1, 9), Ver(2, 0), Ver(1, 10)
print(v1 < v2, v1 > v2, v1 < v3)
print(sorted([v2, v3, v1]))
print(max(v1, v2, v3), min(v1, v2, v3))
True False True
[Ver(1.9), Ver(1.10), Ver(2.0)]
Ver(2.0) Ver(1.9)
v1 > v2works even though only__lt__exists: Python flips it tov2 < v1.- Comparing tuples gives the right version order:
(1, 9) < (1, 10), which text comparison would get wrong (lesson 4.1).
But <= is not available:
v1 <= v2
TypeError: '<=' not supported between instances of 'Ver' and 'Ver'
Writing all of __le__, __gt__ and __ge__ is repetitive. The decorator functools.total_ordering fills in the rest from __eq__ and one of <, <=, >, >=:
from functools import total_ordering
@total_ordering
class Ver2(Ver):
pass
w1 = Ver2(1, 9)
w2 = Ver2(2, 0)
print(w1 <= w2, w1 >= w2, w1 > w2, w1 != w2, w1 == Ver2(1, 9))
True False False True True
(Lesson 13.11 shows that @dataclass(order=True) can also do this.)
7. In-place operators
x += y is not always x = x + y. If the class defines __iadd__, += calls that, and it usually changes the object itself and returns it. If not, Python falls back to x = x + y, which builds a new object (lessons 7.2 and 2.6):
class Money:
def __init__(self, c):
self.c = c
def __add__(self, o):
return Money(self.c + o.c)
def __iadd__(self, o):
self.c += o.c
return self
def __repr__(self):
return f"Money({self.c})"
x = Money(1)
y = x
x += Money(4)
print(x, y, x is y)
x = Money(1)
y = x
x = x + Money(4)
print(x, y, x is y)
Money(5) Money(5) True
Money(5) Money(1) False
The += changed the shared object, so y saw it. The + made a new object, so y kept the old value. __iadd__ must return self. Many classes (and all immutable ones) simply do not define it.
8. Other useful operators
@(__matmul__) is for matrix multiplication; Python has no built-in type that uses it, but libraries do:
class Matrix:
def __init__(self, rows):
self.rows = rows
def __matmul__(self, o):
return Matrix([[sum(a * b for a, b in zip(r, col)) for col in zip(*o.rows)]
for r in self.rows])
def __getitem__(self, ij):
i, j = ij
return self.rows[i][j]
def __repr__(self):
return f"Matrix({self.rows})"
A = Matrix([[1, 2], [3, 4]])
B = Matrix([[0, 1], [1, 0]])
print(A @ B)
print((A @ B)[0, 1])
Matrix([[2, 1], [4, 3]])
1
A[0, 1] passes the tuple (0, 1) to __getitem__ (lesson 8.1).
__call__can make a polynomial or any function-like object (lesson 13.7).bool(obj)uses__bool__, andabs,round,intuse their own methods (lesson 13.7).
9. Guidelines
| Do | Do not |
|---|---|
| use operators for natural meanings | make + mean something surprising |
return a new object from +, -, * |
change the operands |
return NotImplemented for unknown types |
raise errors or return None |
define __hash__ with __eq__ for immutable value objects |
hash a mutable object |
use total_ordering or dataclass(order=True) |
write all six comparison methods by hand |
make == consistent with ordering |
let a == b and not (a < b or b < a) disagree |
Worked example: an amount of money
Write a Money class (in whole cents) that adds, subtracts and multiplies by a number, compares and sorts, works with sum, can be a dictionary key, and prints nicely.
from functools import total_ordering
@total_ordering
class Money:
def __init__(self, cents):
self.cents = cents
def __repr__(self):
return f"Money({self.cents})"
def __str__(self):
return f"${self.cents / 100:,.2f}"
def __eq__(self, other):
return isinstance(other, Money) and self.cents == other.cents
def __hash__(self):
return hash(self.cents)
def __lt__(self, other):
if not isinstance(other, Money):
return NotImplemented
return self.cents < other.cents
def __add__(self, other):
if not isinstance(other, Money):
return NotImplemented
return Money(self.cents + other.cents)
def __radd__(self, other):
return self if other == 0 else self.__add__(other)
def __sub__(self, other):
if not isinstance(other, Money):
return NotImplemented
return Money(self.cents - other.cents)
def __mul__(self, k):
if not isinstance(k, (int, float)):
return NotImplemented
return Money(round(self.cents * k))
__rmul__ = __mul__
def __bool__(self):
return self.cents != 0
prices = [Money(250), Money(1999), Money(75)]
print(sum(prices))
print(max(prices), min(prices))
print(sorted(prices))
print(Money(1000) * 1.5, 2 * Money(75), Money(500) - Money(120))
print(Money(100) == Money(100), Money(100) < Money(200) <= Money(200))
print({Money(100): "tea"}[Money(100)], bool(Money(0)))
$23.24
$19.99 $0.75
[Money(75), Money(250), Money(1999)]
$15.00 $1.50 $3.80
True True
tea False
| Feature | How |
|---|---|
sum(prices) |
__radd__ handles the starting 0 |
max, min, sorted |
__lt__, completed by total_ordering |
| usable as a dictionary key | __eq__ and __hash__ from the same data |
Money(1000) * 1.5 and 2 * Money(75) |
__mul__ and __rmul__, rounding to whole cents |
| a nice print | __str__ for users, __repr__ for developers |
Money is kept in whole cents (integers) to avoid floating-point errors (lesson 3.4). The amounts are made up.
Common mistakes
- Returning
Noneor raising for an unknown operand type instead of returningNotImplemented. - Defining
__eq__and forgetting__hash__, which makes the class unhashable. - Changing the operands inside
__add__. - Forgetting
__radd__/__rmul__, sosumor3 * objfail. - Defining only
__lt__and expecting<=to work (usetotal_ordering). - Forgetting
return selfin__iadd__. - Hashing an object that can change.
Key takeaways
- Operators call special methods:
a + bisa.__add__(b),a == bisa.__eq__(b),a < bisa.__lt__(b). - Return
NotImplementedfor operand types you do not handle; Python then tries the reflected method (__radd__,__rmul__) before raisingTypeError. - Defining
__eq__removes the default hash; define__hash__too for immutable value objects. __lt__plus@functools.total_orderinggives all comparisons,sorted,minandmax.__iadd__changes the object in place and returnsself;+makes a new object.
Practice
1. What method makes 3 * vec work when Vec defines __mul__?
Show answer
__rmul__. Python tries it on the right operand after int.__mul__ returns NotImplemented. A simple way is __rmul__ = __mul__.
2. What should __add__ return when other is a type it cannot add?
Show answer
NotImplemented (the value, not an exception).
3. Why does hash(obj) fail after you define only __eq__?
Show answer
Python removes the default __hash__ when __eq__ is defined, so that equal objects cannot have different hashes. Define __hash__ too.
4. Which decorator saves you from writing __le__, __gt__ and __ge__?
Show answer
functools.total_ordering, given __eq__ and one ordering method such as __lt__.
5. What is the difference between x += y with __iadd__ and x = x + y?
Show answer
__iadd__ usually changes the same object (which other names also see) and returns it. x + y creates a new object and leaves the old one alone.
6. Why does sum([Money(1), Money(2)]) need __radd__?
Show answer
sum starts with 0 and computes 0 + Money(1), so Python needs Money.__radd__ to handle a number on the left.