Sub topic 8
Reflected operators and returning NotImplemented
This chapter assumes you can write a class with __init__ and __repr__. It also assumes you have seen __add__ and __mul__ on a small class such as a vector. Here you will learn how Python picks which operand handles a binary operator. You will also learn why unsupported operand types should produce NotImplemented and not an exception.
Why an operator needs two chances
In a + b, Python asks a first. If a cannot handle b, Python asks b through a second method. That second method is the reflected method, and its name has an r after the leading underscores: __radd__, __rmul__, and so on.
Without this second chance, 3 * Vector(1, 2) could never work. The built-in int knows nothing about Vector, so int.__mul__ cannot handle it. Python then tries Vector.__rmul__(vector, 3). Note the argument order: self is always the object whose method runs, and other is the other operand.
| Expression | First call | Fallback call |
|---|---|---|
| `a + b` | `a.__add__(b)` | `b.__radd__(a)` |
| `a - b` | `a.__sub__(b)` | `b.__rsub__(a)` |
| `a * b` | `a.__mul__(b)` | `b.__rmul__(a)` |
| `a / b` | `a.__truediv__(b)` | `b.__rtruediv__(a)` |
| `a == b` | `a.__eq__(b)` | `b.__eq__(a)` |
| `a < b` | `a.__lt__(b)` | `b.__gt__(a)` |
Comparisons have no r methods. Each comparison reflects onto its mirror: < onto >, <= onto >=, and == onto ==.
NotImplemented is a signal, not an error
NotImplemented is a built-in singleton value. A binary method returns it to say "I don't know how to handle this operand type. Ask someone else." It is not an exception, and you return it. You do not raise it.
When both sides return NotImplemented, Python itself raises TypeError, with a standard message that names both types. If your method raised TypeError directly, b would never get its turn. This is why the earlier chapters' operator methods end their type checks with return NotImplemented.
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 __add__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return Vector(self.x + other.x, self.y + other.y)
def __radd__(self, other):
# sum() starts from the integer 0, so 0 + Vector must work.
if isinstance(other, int) and other == 0:
return self
return NotImplemented
print(sum([Vector(1, 2), Vector(3, 4)])) # Vector(4, 6)
try:
Vector(1, 2) + 'a'
except TypeError as e:
print(e) # unsupported operand type(s) for +: 'Vector' and 'str'In sum, the first step is 0 + Vector(1, 2). int.__add__ returns NotImplemented, so Python calls Vector(1, 2).__radd__(0). The 0 special case in __radd__ is what makes sum work. Without it, you would have to call sum(vectors, Vector(0, 0)).
The failing + 'a' case is handled the same way. Vector.__add__ returns NotImplemented, then str has no __radd__, so Python raises the TypeError for you.
Operations where order matters
For commutative operations such as + on numbers, the reflected method can reuse the forward one. The earlier chapter's __rmul__ = __mul__ is safe because scalar multiplication gives the same result in either order.
That shortcut is wrong for subtraction, division, and any operation where a - b differs from b - a. Here other is the left operand, so you must compute in that order.
class Num:
def __init__(self, value):
self.value = value
def __repr__(self):
return f'Num({self.value!r})'
def __sub__(self, other):
if isinstance(other, Num):
other = other.value
elif not isinstance(other, (int, float)):
return NotImplemented
return Num(self.value - other)
def __rsub__(self, other):
# Called for `other - self`, so other is the LEFT operand.
if not isinstance(other, (int, float)):
return NotImplemented
return Num(other - self.value)
print(Num(10) - 3) # Num(7)
print(3 - Num(10)) # Num(-7), via __rsub__If you had written __rsub__ = __sub__, then 3 - Num(10) would give Num(7), which is silently wrong. Nothing raises an error, so this bug is easy to miss.
Subclasses get priority
Python normally tries the left operand first. There is one exception. If the right operand's type is a subclass of the left operand's type, and it provides its own version of the reflected method, Python calls the right operand's reflected method first. This lets a subclass override how it combines with its parent class.
class A:
def __add__(self, other):
print('A.__add__')
return NotImplemented
def __radd__(self, other):
print('A.__radd__')
return 'A result'
class B(A):
def __radd__(self, other):
print('B.__radd__')
return 'B result'
print(A() + B()) # B.__radd__ runs first, then prints: B result
try:
A() + A()
except TypeError:
print('same type: no reflected call')The first expression prints B.__radd__ and then B result. A.__add__ never runs. The second expression prints A.__add__, then same type: no reflected call. Python does not try A.__radd__ when both operands have the same type, because it would be the same method that already declined.
Comparisons and equality
The same pattern applies to == and the ordering operators. Return NotImplemented for foreign types, and Python tries the reflected comparison. If that also fails, the result depends on the operator:
- For
==and!=, Python falls back to comparing identity, so you getFalseandTrueand no error. - For
<,<=,>, and>=, Python raisesTypeError.
This is why Version(1, 0) == 'x' quietly gives False while Version(1, 0) < 'x' raises. Returning False from __eq__ for foreign types instead of NotImplemented also works for the direct case. It blocks the other operand from deciding, and it breaks symmetry with types that do know how to compare to yours.
Common errors
- Raising
TypeErrorinside__add__. The right operand never gets a chance. ReturnNotImplemented. - Writing
raise NotImplementedor returningNotImplementedError.NotImplementedis a value.NotImplementedErroris an exception class for abstract methods. They are unrelated. RaisingNotImplementeditself fails with aTypeErrorabout exceptions. - Aliasing
__rsub__ = __sub__or the same for division, which gives reversed results. - Forgetting that
selfis the right operand inside a reflected method. - Expecting reflection for same-type operands. It does not happen.
- Checking
isinstance(other, (int, float))and forgettingbool.boolis a subclass ofint, soVector(1, 2) * Trueis accepted. Decide whether that is acceptable for your class.
Exercise
A class Money stores an amount. Money(5) + Money(3) works. You also want sum([Money(5), Money(3)]) to work. What happens in the first step of sum, and what must __radd__ do?
Show answer
sum starts with the integer 0, so the first step is 0 + Money(5). int.__add__ returns NotImplemented, so Python calls Money(5).__radd__(0). __radd__ must return self when other is the integer 0, and return NotImplemented for other types.
Exercise
Given class P: pass and class Q(P): def __radd__(self, other): return 'Q', what does P() + Q() return, and why? What changes if Q does not define __radd__?
Show answer
It returns 'Q'. Q is a subclass of P and provides its own __radd__, so Python tries Q().__radd__(P()) before looking at the left operand. If Q does not define __radd__, there is no priority rule. P has no __add__, and Q has no reflected method of its own to call, so the expression raises TypeError.