Sub topic 8
Reflected operators and returning NotImplemented
This chapter assumes you can define classes and instance methods, and that you have seen __add__ and __mul__ on a class like Vector. Here you will see what happens when the left operand cannot handle the right one, and how NotImplemented makes your classes cooperate with other types.
How Python evaluates a + b
Python does not call a.__add__(b) and stop. It follows a protocol:
- Call
type(a).__add__(a, b). - If that method is missing or returns
NotImplemented, calltype(b).__radd__(b, a). - If that also fails, raise
TypeError.
The "r" stands for reflected: the same operation with the operands swapped. If type(b) is a subclass of type(a) and overrides the reflected method, Python tries b.__radd__ first.
NotImplemented is a return value, not an exception
NotImplemented is a built-in singleton. Returning it tells Python "I do not know how to handle this operand, ask the other side." Raising NotImplementedError is different: it aborts the operation immediately and blocks the other operand from getting a turn.
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 __mul__(self, scalar):
if not isinstance(scalar, (int, float)):
return NotImplemented
return Vector(self.x * scalar, self.y * scalar)
__rmul__ = __mul__
print(Vector(1, 2) * 3) # Vector(3, 6)
print(3 * Vector(1, 2)) # Vector(3, 6)
try:
Vector(1, 2) * 'a'
except TypeError as e:
print(e)For 3 * Vector(1, 2), int.__mul__ returns NotImplemented because it does not know Vector. Python then calls Vector.__rmul__, which succeeds. For Vector(1, 2) * 'a', both sides return NotImplemented, so Python raises a TypeError that names both types.
Non-commutative operations
Aliasing __rmul__ = __mul__ works only when order does not matter. For subtraction, the reflected method receives the operands in the original order, so you must handle it explicitly.
class Money:
def __init__(self, amount):
self.amount = amount
def __repr__(self):
return f'Money({self.amount!r})'
def __sub__(self, other):
if isinstance(other, Money):
other = other.amount
elif not isinstance(other, (int, float)):
return NotImplemented
return Money(self.amount - other)
def __rsub__(self, other):
# Called for other - self, so self is the right operand.
if not isinstance(other, (int, float)):
return NotImplemented
return Money(other - self.amount)
print(Money(10) - 3) # Money(7)
print(100 - Money(30)) # Money(70)Common errors
- Raising
TypeErrorinside__add__. This stops Python from trying the other operand. ReturnNotImplementedinstead. - Returning
FalseorNonefor an unsupported type. Python treats that as a real result. - Swapped operands in
__rsub__.selfis the right operand, so computeother - self. - Forgetting
__radd__forsum().sumstarts from0, so0 + objneeds__radd__.
Exercise
Given a class Meters that defines only __add__, which returns NotImplemented for non-Meters operands, what does 5 + Meters(2) do, and why?
Show answer
It raises TypeError. int.__add__ returns NotImplemented, so Python tries Meters.__radd__, which does not exist. Defining __radd__ would make it work.