Sub topic 17
When to overload and what to avoid
This chapter assumes you can define classes in Python and have seen the special methods from earlier chapters: __repr__, __eq__, __hash__, the ordering methods, and the arithmetic and reflected operators. Here the question changes from how to overload to whether you should.
The core rule: match the built-in meaning
An overloaded operator should do what a reader expects from the same operator on built-in types. + on numbers adds. On sequences it concatenates. On a Vector, adding components is the natural reading. If you can't describe your operator in terms people already know, use a named method.
class Path:
def __init__(self, *parts):
self.parts = parts
def __repr__(self):
return f'Path{self.parts!r}'
def join(self, name):
return Path(*self.parts, name)
def __truediv__(self, name):
if not isinstance(name, str):
return NotImplemented
return self.join(name)
p = Path('usr')
print(p / 'bin') # Path('usr', 'bin')
print(p.join('local')) # Path('usr', 'local')Here / is a well-known path idiom, and a plain join method exists beside it. When an operator reads oddly, the named method is the safer interface.
Common pitfalls
| Pitfall | What goes wrong | Fix |
|---|---|---|
| Defining `__eq__` without `__hash__` | Python sets `__hash__` to `None`, so instances can't go in sets or be dict keys | Define both, from the same fields |
| Hashing a mutable object | Changing a field after insertion makes the object unfindable in a set or dict | Hash only immutable fields, or keep the object immutable |
| Raising `TypeError` in a binary operator | Python never tries the other operand's reflected method | Return `NotImplemented` |
| Returning a new object from `__iadd__` on a mutable type | `a += b` rebinds the name, so other references to `a` don't see the change | Mutate `self` and return `self` |
| Comparing with `isinstance` against a subclass-unfriendly type | Equality breaks across related classes | Return `NotImplemented` for foreign types |
| Giving `__repr__` side effects or exceptions | Debuggers and logs fail at the worst time | Keep it simple and read-only |
Consistency between related methods
Several methods must agree with each other. Two equal objects must have equal hashes. If a == b is true, then a <= b and a >= b should be true, and a < b should be false. If __len__ returns 0 and you define no __bool__, the object is falsy, so check that this is what you want.
class Money:
def __init__(self, cents):
self.cents = cents
def __repr__(self):
return f'Money({self.cents})'
def __eq__(self, other):
if not isinstance(other, Money):
return NotImplemented
return self.cents == other.cents
def __hash__(self):
return hash(self.cents)
def __add__(self, other):
if not isinstance(other, Money):
return NotImplemented
return Money(self.cents + other.cents)
total = Money(150) + Money(250)
print(total) # Money(400)
print(total == Money(400)) # True
print(hash(total) == hash(Money(400))) # True
try:
Money(5) + 5
except TypeError as e:
print(e) # unsupported operand type(s) for +: 'Money' and 'int'Returning NotImplemented produces the standard TypeError message, so users see the same error as with built-in types.
A short checklist
- Define
__repr__first. It helps every other debugging step. - Return new objects from
+,-,*. Mutate only in the in-place forms. - Return
NotImplementedfor unsupported operand types. - Keep
__eq__,__hash__and ordering consistent. - Don't overload an operator for an unrelated meaning, such as
<<to append to a list of log lines. - Prefer a plain method when the operation has no obvious symbol.
Exercise
A class defines __eq__ comparing two fields but no __hash__. What happens when you put an instance in a set, and how do you fix it?
Show answer
Python sets __hash__ to None when a class defines __eq__ without __hash__, so adding an instance to a set raises TypeError: unhashable type. Fix it by defining __hash__ from the same fields, for example hash((self.a, self.b)), and only if those fields don't change after the object is created.