Sub topic 7
Overloading arithmetic operators
When Python evaluates a + b, it does not add anything itself. It asks the left operand's type to do the work by calling a.__add__(b). If your class defines __add__, your code runs. This chapter covers the binary arithmetic methods, how Python picks which one to call, and the errors that come up when you write them.
This chapter assumes you can define classes with __init__ and __repr__, and that you know isinstance. Reflected methods such as __radd__ and in-place methods such as __iadd__ get their own chapters. Here they appear only where needed.
The operator-to-method table
Each arithmetic operator corresponds to one method on the left operand's type.
| Expression | Method called | Typical meaning |
|---|---|---|
| `a + b` | `a.__add__(b)` | addition |
| `a - b` | `a.__sub__(b)` | subtraction |
| `a * b` | `a.__mul__(b)` | multiplication |
| `a / b` | `a.__truediv__(b)` | true division |
| `a // b` | `a.__floordiv__(b)` | floor division |
| `a % b` | `a.__mod__(b)` | remainder |
| `a ** b` | `a.__pow__(b)` | exponent |
| `a @ b` | `a.__matmul__(b)` | matrix multiplication |
| `divmod(a, b)` | `a.__divmod__(b)` | quotient and remainder |
Python looks these methods up on the type, not on the instance. Assigning obj.__add__ = something on a single object has no effect on obj + 1.
Each method receives the left operand as self and the right operand as its argument. It should return a new object and leave both operands unchanged.
A first implementation
This Vector supports addition and subtraction with other vectors, and multiplication and division by a number.
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 __sub__(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)
def __truediv__(self, scalar):
if not isinstance(scalar, (int, float)):
return NotImplemented
return Vector(self.x / scalar, self.y / scalar)
a = Vector(1, 2)
b = Vector(3, 4)
print(a + b) # Vector(4, 6)
print(b - a) # Vector(2, 2)
print(a * 3) # Vector(3, 6)
print(a / 2) # Vector(0.5, 1.0)
print(a) # Vector(1, 2), unchanged
try:
a + 5
except TypeError as e:
print(e) # unsupported operand type(s) for +: 'Vector' and 'int'Two details matter here. Every method builds a new Vector instead of modifying self. And each method checks the type of the other operand first.
Returning NotImplemented
NotImplemented is a special built-in value. It does not mean "error". It means "I don't know how to handle this operand, ask someone else." Python then tries the right operand's reflected method (for +, that is b.__radd__(a)). If that also declines, Python raises the TypeError you saw above.
The diagram omits two cases. If b's type is a subclass of a's type and overrides __radd__, Python tries b.__radd__(a) first. And when both operands have the same type, the reflected method is skipped.
Returning NotImplemented instead of raising TypeError yourself keeps your class cooperative. Suppose someone writes a Matrix class that knows how to multiply by a Vector. If Vector.__mul__ raised TypeError directly, Vector * Matrix would fail before Matrix.__rmul__ got a chance. Returning NotImplemented lets that method run.
Domain errors are different
NotImplemented is for operand types you don't recognize. If the type is right but the operation makes no sense, raise a normal exception. Here is a Money class that refuses to add different currencies.
from decimal import Decimal
class Money:
def __init__(self, amount, currency):
self.amount = Decimal(amount)
self.currency = currency
def __repr__(self):
return f'Money({str(self.amount)!r}, {self.currency!r})'
def __add__(self, other):
if not isinstance(other, Money):
return NotImplemented
if other.currency != self.currency:
raise ValueError(
f'cannot add {self.currency} and {other.currency}'
)
return Money(self.amount + other.amount, self.currency)
print(Money('1.50', 'USD') + Money('2.25', 'USD')) # Money('3.75', 'USD')
try:
Money('1', 'USD') + Money('1', 'EUR')
except ValueError as e:
print(e) # cannot add USD and EURA ValueError is the right choice here. Passing the operation to another type would not help, because the problem is the values and not the types.
Choosing which types to accept
The isinstance(scalar, (int, float)) check in Vector is simple, but it has gaps.
boolis a subclass ofint, soVector(1, 2) * Trueworks and givesVector(1, 2).FractionandDecimalare rejected, soVector(1, 2) * Fraction(1, 2)returnsNotImplementedand ends in aTypeError.numbers.Realacceptsint,floatandFraction, but notDecimal.
Pick the check that matches your intent and document it. A strict check is easier to reason about. A broad check, or attempting the operation and catching TypeError, is friendlier to other numeric types.
Subclasses and the result type
Vector(...) is hard-coded in each method. If someone subclasses Vector, adding two Vector3D-style subclass instances returns a plain Vector and loses the subclass. Using type(self) keeps the subclass, as long as the subclass constructor takes the same arguments.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f'{type(self).__name__}({self.x!r}, {self.y!r})'
def __add__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return type(self)(self.x + other.x, self.y + other.y)
class Velocity(Vector):
pass
print(Velocity(1, 2) + Velocity(3, 4)) # Velocity(4, 6)If your subclasses change the constructor signature, type(self)(...) breaks. In that case, keep Vector(...) or give subclasses their own __add__.
Less common operators
The remaining operators follow the same pattern. __pow__ is the one exception. It takes an optional third argument, which is used by the three-argument form pow(a, b, mod).
class Mod7:
def __init__(self, n):
self.n = n % 7
def __repr__(self):
return f'Mod7({self.n})'
def __pow__(self, exponent, modulo=None):
if not isinstance(exponent, int):
return NotImplemented
return Mod7(pow(self.n, exponent, 7))
def __floordiv__(self, other):
if not isinstance(other, int):
return NotImplemented
return Mod7(self.n // other)
print(Mod7(3) ** 4) # Mod7(4)
print(Mod7(6) // 2) # Mod7(3)The bitwise operators (&, |, ^, <<, >>) work the same way, through __and__, __or__, __xor__, __lshift__ and __rshift__. Sets use | and & for union and intersection, and pathlib.Path uses / to join paths. Both are established uses of an operator for something other than arithmetic.
Common errors
- Returning
None. A method that forgetsreturnproducesNone, and the expression silently evaluates toNone. - Mutating
self.c = a + bshould not changea. Callers who share objects will see strange bugs. - Raising
TypeErrorfor unknown types. This blocks the other operand's reflected method. - Forgetting the right operand's type.
a + bworks but5 + afails. That is a reflected-method problem, covered in the next chapter. - Skipping
__repr__. Without it, errors and test output show<Vector object at 0x...>.
Exercise
A Temperature class defines __add__ that does return Temperature(self.deg + other.deg) with no type check. What happens for Temperature(20) + 5, and how would you fix the method?
Show answer
It raises AttributeError: 'int' object has no attribute 'deg', because the method reads other.deg on an int. The fix is to add if not isinstance(other, Temperature): return NotImplemented before the return. Python then raises a clear TypeError or tries the other operand's reflected method.
Exercise
You are writing __sub__ for Money, and Money('5', 'USD') - Money('1', 'EUR') is called. Should the method return NotImplemented, raise ValueError, or raise TypeError? Explain.
Show answer
Raise ValueError. Both operands are Money, so the types are supported and no other class's reflected method could help. The values (the mismatched currencies) are the problem. NotImplemented is only for operand types the method does not recognize.