Sub topic 17
When to overload and what to avoid
This chapter covers design decisions rather than new syntax. It assumes you know the special methods from earlier chapters: __repr__, __eq__ and __hash__, the arithmetic and reflected operators, the container and iteration protocols, and __getattr__. The question now is when using them helps and when it hurts.
A test for whether to overload
Operator overloading is worth it when the operator's meaning is already familiar for your type. Readers should be able to guess what a + b does without opening your class.
| Good fit | Poor fit | Column |
|---|---|---|
| `Vector + Vector`, `Money + Money`, `Matrix @ Matrix` | `User + User` to "merge accounts" | |
| `len(playlist)`, `song in playlist` | `-order` to mean "cancel order" | |
| `with Timer():` for setup and cleanup | `query1 | query2` when no one expects set-like behavior |
| `Version(1, 2) < Version(1, 3)` | `a << b` to mean "send message" |
If you hesitate over what an operator should do, write a method such as merge() or cancel(). A named method documents itself, and an operator does not.
Keep operators predictable
Several rules keep overloaded operators unsurprising.
- Return a new object from binary operators.
a + bshould leaveaandbunchanged. - Return
NotImplementedfor unsupported types. This lets Python try the other operand's reflected method. RaisingTypeErroryourself skips that step and breaks interoperability. - Raise an exception for supported types with invalid values. The operand type is fine but the operation is meaningless, so
ValueErroris the right signal. - Keep related operators consistent. If
a == b, thenhash(a) == hash(b), anda <= bshould agree witha < b or a == b. - Return the type users expect. Comparisons return
bool.+on a value type returns the same type.
The Money class below follows these rules.
class Money:
def __init__(self, cents, currency):
self.cents = cents
self.currency = currency
def __repr__(self):
return f'Money({self.cents!r}, {self.currency!r})'
def __add__(self, other):
if not isinstance(other, Money):
return NotImplemented # wrong type: let Python decide
if other.currency != self.currency:
raise ValueError('currency mismatch') # right type, bad value
return Money(self.cents + other.cents, self.currency)
print(Money(100, 'USD') + Money(250, 'USD')) # Money(350, 'USD')
try:
Money(1, 'USD') + 5
except TypeError as e:
print(e) # unsupported operand type(s) for +: 'Money' and 'int'
print(sum([Money(1, 'USD'), Money(2, 'USD')], Money(0, 'USD'))) # Money(3, 'USD')The sum() call shows a common gotcha. sum() starts from the integer 0 by default, so 0 + Money(...) fails because Money has no __radd__. Pass a start value, or add __radd__ that accepts 0. Only add __radd__ for 0 if you want that behavior, because it widens what your type accepts.
Common pitfalls
Mutable objects with a value-based hash
Defining __eq__ and __hash__ from mutable fields lets you break a set or dict without any error.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
if not isinstance(other, Point):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))
p = Point(1, 2)
seen = {p}
p.x = 99
print(p in seen) # False: the set filed p under its old hash
print(len(seen)) # 1: the object is still in there, unreachable by lookupPython does not enforce immutability. Hash only fields that never change after construction. If the object must be mutable, leave __hash__ undefined. Defining __eq__ alone sets __hash__ to None, which is the correct default for mutable types.
In-place operators that alias
a += b calls __iadd__ if it exists and rebinds a to whatever it returns. Mutable types usually modify self and return it, so every name bound to that object sees the change. Immutable types fall back to __add__ and create a new object.
a = [1]
b = a
a += [2]
print(b) # [1, 2]: same object, mutated
t = (1,)
u = t
t += (2,)
print(u) # (1,): new object, u unchangedDefine __iadd__ only for types that are mutable by design. Never return something other than self from it unless you intend to rebind. A forgotten return self makes the variable None.
Recursion in `__getattr__`
__getattr__ runs only when normal lookup fails. If it reads an attribute that does not exist yet, it calls itself forever. This happens with copy and pickle, which create instances without running __init__.
class Proxy:
def __init__(self, target):
self._target = target
def __getattr__(self, name):
if name == '_target': # guard: avoid infinite recursion
raise AttributeError(name)
return getattr(self._target, name)
print(Proxy([3, 1, 2]).count(1)) # 1
empty = Proxy.__new__(Proxy) # no __init__ ran, so _target is missing
try:
empty.anything
except AttributeError as e:
print('AttributeError:', e) # AttributeError: _targetRaise AttributeError for names you do not handle. Other exceptions break hasattr() and getattr(obj, name, default).
Other traps
__bool__and__len__disagree. Python tries__bool__first and falls back to__len__. A container whose__len__is 0 is falsy, andif obj:then reads as "is it non-empty?". Do not use that test to mean "is it notNone". Writeobj is not None.__repr__that raises. Debuggers, logs and tracebacks call it, so an exception inside it hides the real error. Keep it simple and only read attributes you set in__init__.- Partial ordering. Defining
__lt__that is not a consistent total order makessorted()give arbitrary results. Compare tuples of fields, asVersiondoes, instead of inventing rules. - Cleverness in
__exit__. Returning a truthy value suppresses the exception. ReturnFalseorNoneunless suppression is the point of the class. - Subclass surprises. If
Vector.__add__returnsVector(...)explicitly, a subclass's+returns the base class. Usetype(self)(...)if you want the subclass preserved, and document the choice.
Review checklist
Before shipping a class with special methods, check each item.
- Can you replace each operator with a clearly named method without losing readability? If not, the operator earns its place.
- Do
__eq__and__hash__use the same immutable fields? - Do binary operators return
NotImplementedfor unknown types? - Do you have tests for mixed-type cases, such as
3 * v,v * 3andv + 3? - Does
repr()work on every instance, including partly built ones? - Is any in-place operator documented as mutating?
Exercise
A teammate writes a mutable Account class with __eq__ comparing balance and __hash__ returning hash(self.balance). They store accounts in a set, then deposit money into one. What goes wrong, and what are two ways to fix it?
Show answer
After the deposit, the account's hash changes, so the set looks in the wrong place. account in the_set returns False even though the object is still stored, and duplicates can slip in. Fix 1: compare and hash a field that never changes, such as an immutable account ID. Fix 2: remove __hash__ (leave only __eq__) so the class is unhashable and cannot be put in a set by mistake.
Exercise
Money(1, 'USD') + 5 raises TypeError and Money(1, 'USD') + Money(1, 'EUR') raises ValueError. Why is __add__ written to produce different exceptions, and which mechanism produces the TypeError?
Show answer
An integer is the wrong type, so __add__ returns NotImplemented. Python then tries int.__radd__, which also returns NotImplemented, and Python itself raises TypeError. A Money in another currency is a supported type with an invalid value, so __add__ raises ValueError directly.