Prerequisites
- !Operator overloading basics and special methods
- !Equality, hashing, and how sets and dicts use keys
What You'll Learn
- 1Explain why dunder methods are looked up on the class, not the instance
- 2Write repr and str output that makes debugging faster
- 3Keep equality and hash consistent so objects work in sets and dicts
- 4Use reflected operators to support mixed-type arithmetic
- 5Implement container protocols that make a custom object feel built in
Dunder methods are the hooks behind every Python operator, every built-in conversion, and every container behaviour you rely on. Defining them is easy; defining them correctly means honouring contracts that the rest of the language assumes, from hash consistency to the promise that a representation can reconstruct the object. Break one of those assumptions and your class still appears to work, until somebody puts it in a set or passes it to a library you did not write.
Special methods are the class's public protocol
Python never looks up a special method on the instance. When you write a + b, the interpreter consults the type of a for __add__, then the type of b for __radd__, and only falls back to an error if both decline. Two consequences follow: defining a dunder on an instance does nothing, and subclasses automatically inherit protocol behaviour from their parents. The lookup is also why len(obj) calls __len__ but obj.__len__() is discouraged, and why operators work even on instances of classes whose methods you never called directly.
| Protocol family | Common members | What it enables |
|---|---|---|
| Object representation | __repr__, __str__, __format__ | Debugging, logging, f-strings |
| Comparison and hashing | __eq__, __lt__, __hash__ | Sorting, sets, dict keys |
| Arithmetic | __add__, __mul__, reflected variants | Expressions with custom types |
| Containers | __len__, __getitem__, __contains__ | Indexing, membership, iteration |
| Context and lifetime | __enter__, __exit__, __del__ | with statements and cleanup |
Treat the table as a checklist rather than a menu. Implementing everything is a common beginner mistake; implementing the subset your type genuinely participates in is the discipline.
repr, str, and the art of a useful string
repr aims at developers and should be unambiguous, ideally something you could paste back into a console to recreate the object. str aims at users and should be readable. When str is not defined, Python falls back to repr, which is why a class that only implements repr still produces decent output in print statements.
import math
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 __str__(self):
return f"({self.x}, {self.y})"
def magnitude(self):
return math.hypot(self.x, self.y)
v = Vector(3, 4)
print(str(v)) # (3, 4)
print(repr(v)) # Vector(3, 4)
print(f"magnitude {v.magnitude():.2f}") # magnitude 5.00
Using !r inside the representation matters for strings, where the quotes distinguish Vector('a', 'b') from Vector(a, b), and for floats where precision could be lost. A representation that silently drops information forces readers to guess at types, and a representation that includes object addresses, the default object.__repr__, tells you nothing about state.
Equality, hashing, and the container contract
Objects that compare equal must hash equally, or collections misbehave in ways that look like data loss. A value added to a set under one hash and searched for under another simply disappears. The converse is not required: unequal objects may share a hash, at the cost of slower lookups.
class Money:
def __init__(self, amount, currency="USD"):
self.amount = amount
self.currency = currency
def __eq__(self, other):
if not isinstance(other, Money):
return NotImplemented
return (self.amount, self.currency) == (other.amount, other.currency)
def __hash__(self):
return hash((self.amount, self.currency))
def __repr__(self):
return f"Money({self.amount!r}, {self.currency!r})"
prices = {Money(5), Money(5), Money(7)}
print(len(prices)) # 2
print(Money(5) in prices) # True
print({Money(5): "discount"}[Money(5)]) # discount
Returning NotImplemented rather than raising an error is the polite protocol: it tells the interpreter this type cannot compare with the other, allowing the reflected operation to run and finally producing a sensible False for ==. Mutable objects that define equality by fields but are stored in sets create a second trap, since changing a field after insertion breaks the set's ability to find the item. Either freeze the relevant fields, or exclude the mutable parts from the hash and accept that equal-but-different-hash states are impossible by construction.
Arithmetic and reflected methods
Numeric types are usually better served by returning a new object of the same class rather than mutating in place, which keeps expressions composable and allows the interpreter to try the other operand's reflected method when types differ.
class Vector2:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
if isinstance(other, Vector2):
return Vector2(self.x + other.x, self.y + other.y)
if isinstance(other, (int, float)):
return Vector2(self.x + other, self.y + other)
return NotImplemented
__radd__ = __add__
def __mul__(self, scalar):
if not isinstance(scalar, (int, float)):
return NotImplemented
return Vector2(self.x * scalar, self.y * scalar)
def __iadd__(self, other):
result = self + other
self.x, self.y = result.x, result.y
return self
def __repr__(self):
return f"Vector2({self.x!r}, {self.y!r})"
a = Vector2(1, 2)
print(a + Vector2(3, 4)) # Vector2(4, 6)
print(a + 10) # Vector2(11, 12)
print(10 + a) # Vector2(11, 12)
a += Vector2(5, 5)
print(a) # Vector2(6, 7)
Sharing __radd__ with __add__ works here because addition of these components is commutative, and the isinstance checks make both directions safe. The in-place method must return the object itself, which is the contract behind +=; returning None breaks assignment silently and produces confusing errors later. Note also that defining __eq__ without __hash__ makes the class unhashable by default, a deliberate language rule that prevents exactly the inconsistency described earlier.
Container protocols that feel native
An object that supports len, indexing, membership, and iteration fits into the language without adapters. Implement __getitem__ and iteration often come for free, because Python falls back to indexed access when no __iter__ is defined, though an explicit iterator is clearer and faster.
class Grid:
def __init__(self, rows):
self.rows = rows
def __len__(self):
return len(self.rows)
def __getitem__(self, index):
if isinstance(index, slice):
return Grid(self.rows[index])
return self.rows[index]
def __contains__(self, value):
return any(value in row for row in self.rows)
def __iter__(self):
for row in self.rows:
yield from row
def __reversed__(self):
for row in reversed(self.rows):
yield from row
grid = Grid([[1, 2], [3, 4], [5, 6]])
print(len(grid), 3 in grid) # 3 True
print(list(grid)) # [1, 2, 3, 4, 5, 6]
print(grid[1]) # [3, 4]
print(grid[0:2]) # Grid([[1, 2], [3, 4]])
print(list(reversed(grid))) # [6, 5, 4, 3, 2, 1]
Supporting slices in __getitem__ means receiving a slice object rather than an integer, which the isinstance check handles, and returning the same wrapper type keeps chaining consistent. Membership falls back to iteration when __contains__ is absent, but an explicit implementation can use indexing or a set for a large speedup. One caution: implementing __getitem__ without __iter__ gives you iteration for free but through the older protocol, which stops unexpectedly if your indexes do not run sequentially, so prefer defining __iter__ explicitly.
Ordering, totality, and what to skip
Ordering comparisons need a total order for sorting to be meaningful. Implementing all four rich comparisons by hand is tedious, so functools.total_ordering fills in the missing ones from __eq__ plus one of __lt__, __le__, __gt__, or __ge__. The generated methods are correct but slower than hand-written ones, so in hot paths write them out.
Some dunder methods are simply not worth defining. __del__ should not be relied on for releasing external resources, because its timing is unpredictable and it can be skipped during interpreter shutdown; use a context manager instead. __getattr__ is for delegating missing attributes and must not be confused with __getattribute__, which intercepts everything and is a well-known source of infinite recursion. And arithmetic on types where the operation has no sensible meaning, such as adding two dates, should raise rather than return a placeholder, because silent nonsense propagates much further than an exception.
Protocols beyond your own code
You implement dunder methods mostly so that other people's code works with your type. Libraries that sort expect ordering, serialization frameworks expect a stable representation, numeric code expects reflected operators, and caching layers expect a hash. Before releasing a public class, scan the protocols of everything that will consume it, and write a small compatibility test for each: put instances in a set, sort a list of them, interpolate one into an f-string, and pass one to the library that will actually see it.
This habit also surfaces missing pieces early. A class that works in your unit tests but fails inside a third-party container almost always lacks __len__ or __iter__. A class that logs as an object address is missing __repr__, which costs debugging time every single time it appears in output. Treat the protocol surface as part of the public API, document which operators are supported, and version the behaviour if downstream code depends on it. Protocol completeness is cheap to add at design time and expensive to bolt on after callers have already worked around its absence.
Common Mistakes
Defining __eq__ without __hash__, then storing instances in sets
Fix: Implement both from the same immutable fields, or accept that the class is intentionally unhashable.
Mutating fields that participate in the hash after insertion into a dict
Fix: Treat hashed fields as immutable, or rebuild the container after an intentional change.
Raising TypeError from a binary operator instead of returning NotImplemented
Fix: Return NotImplemented so the interpreter can try the reflected operation and produce a clean error.
Relying on __del__ to close files or network connections
Fix: Use context managers or explicit close methods so cleanup happens deterministically.
Best Practices
- Make repr round-trippable whenever the object can be constructed from its fields
- Keep equality and hash derived from exactly the same attributes
- Return new objects from operators and only mutate in explicit in-place methods
- Implement just the protocols your type participates in, not every dunder you can name
- Test operators with mixed types to confirm reflected methods behave
Key Takeaways
- Special methods are looked up on the type, which is why instance-level dunders do nothing
- Equal objects must hash equally or sets and dicts lose entries unpredictably
- Return NotImplemented from operators so Python can try the reflected form
- In-place operators must return the object, and __eq__ without __hash__ removes hashing
- Container protocols built from len, getitem, and iter make custom types feel native