Dunder methods
Dunder methods are names with double underscores on both sides, such as __init__ and __len__. Python calls them for language operations: construction, arithmetic, iteration, formatting, and context management.
Detailed Explanation
"Dunder" is short for double underscore. These methods are the hooks of Python's object protocol. You almost never call them directly. You write len(order), and the interpreter calls order.__len__(). You write a + b, and it calls a.__add__(b). You write with lock:, and it calls __enter__ and __exit__.
The set is large and documented in the data model. Construction: __new__, __init__, __del__. Representation: __repr__, __str__, __format__, __bytes__. Comparison: __eq__, __lt__, and the rest; implement __eq__ and __hash__ together if the object must live in a set. Containers: __len__, __getitem__, __setitem__, __contains__, __iter__. Numerics: __add__, __radd__, __iadd__, and many more. Call: __call__. Context: __enter__, __exit__. Attribute access: __getattr__, __getattribute__, __setattr__. Descriptors: __get__, __set__, __delete__.
Implement a dunder when you want your type to behave like a builtin in that slot. A vector class that supports + should implement __add__ and __radd__. A collection should implement __len__ and __iter__. Do not implement a dunder "just in case". An incorrect __eq__ that always returns True will break every dict that uses your objects as keys once you also add __hash__.
__getattr__ runs only after normal lookup fails. __getattribute__ runs on every attribute access and is easy to recurse on (self.name calls it again). Prefer explicit methods and properties over a smart __getattr__.
Names that look like dunders but are not in the data model (__foo__ you invented) pollute the namespace the language reserved. Use a single underscore or a plain name for your own hooks.
dir(obj) and the data model page are the maps. When a builtin rejects your object (len(x) → TypeError: object of type 'X' has no len()), you are missing a dunder, not a decorator.
Code Examples
class Cart:
def __init__(self, items: list[str]):
self._items = list(items)
def __len__(self) -> int:
return len(self._items)
def __contains__(self, sku: object) -> bool:
return sku in self._items
def __repr__(self) -> str:
return f"Cart({self._items!r})"
cart = Cart(["A-1", "B-2"])
print(len(cart), "A-1" in cart) # 2 True
print(cart) # Cart(['A-1', 'B-2'])class Cents:
def __init__(self, value: int):
self.value = value
def __add__(self, other: "Cents") -> "Cents":
if not isinstance(other, Cents):
return NotImplemented
return Cents(self.value + other.value)
def __repr__(self) -> str:
return f"Cents({self.value})"
print(Cents(100) + Cents(50)) # Cents(150)Common Gotchas
Returning `NotImplemented` is not `raise NotImplementedError`
the first lets Python try the reflected operand. The second is an exception. Use `NotImplemented` in arithmetic dunders.
`__eq__` without `__hash__`
if you override equality, Python sets `__hash__` to `None` and the object becomes unhashable. That is correct for mutable types. For immutable ones, implement both.
`__getattribute__` recurses
use `object.__getattribute__(self, name)` or `super()` when you override it.
Do not invent new `__foo__` names
the language reserves that pattern. Your API can be `foo`.