Sub topic 1
How Python maps syntax to special methods
Prerequisites
This chapter assumes you can do the following:
- Define classes and create instances in Python.
- Write instance attributes and regular methods.
- Use built-in types such as
list,dictandtuple. - Write
forloops andwithstatements.
You don't need to know any special methods yet. This chapter introduces the idea, and later chapters cover each group in detail.
What a special method is
A special method, also called a dunder method, is a method whose name starts and ends with double underscores. "Dunder" is short for "double underscore". You have already used one: __init__.
Python does not give +, len(), for or with any magic power over your objects. Each of these is defined as a request to the object's type. When you write len(x), Python asks the type of x to run its __len__ method. When you write a + b, Python asks the type of a to run __add__.
This design is called the Python data model. If your class defines the right methods, its instances work with the same syntax as built-in types. If it doesn't, Python raises an error.
A first example
class Box:
def __init__(self, items):
self.items = list(items)
def __repr__(self):
return f'Box({self.items!r})'
def __len__(self):
return len(self.items)
def __add__(self, other):
if not isinstance(other, Box):
return NotImplemented
return Box(self.items + other.items)
a = Box([1, 2])
b = Box([3])
print(len(a)) # 2
print(a + b) # Box([1, 2, 3])
print(a) # Box([1, 2])The class never calls __len__ or __add__ itself. Python calls them when it sees len(a) and a + b. The print(a) call works because print converts the object to text, which uses __repr__ here. The next chapter covers why.
The syntax-to-method map
The table lists common syntax and the method Python looks for. Each row is covered in a later chapter.
| You write | Python calls | Topic |
|---|---|---|
| `repr(x)` | `type(x).__repr__(x)` | String representations |
| `str(x)`, `print(x)` | `type(x).__str__(x)` | String representations |
| `x == y` | `type(x).__eq__(x, y)` | Equality and hashing |
| `x < y` | `type(x).__lt__(x, y)` | Ordering |
| `bool(x)`, `if x:` | `__bool__`, then `__len__` | Truth value |
| `x + y` | `type(x).__add__(x, y)` | Arithmetic |
| `-x` | `type(x).__neg__(x)` | Unary operators |
| `len(x)` | `type(x).__len__(x)` | Containers |
| `x[i]` | `type(x).__getitem__(x, i)` | Containers |
| `i in x` | `__contains__`, with fallbacks | Containers |
| `for i in x` | `type(x).__iter__(x)` | Iteration |
| `x(args)` | `type(x).__call__(x, args)` | Callables |
| `with x:` | `__enter__` and `__exit__` | Context managers |
| `x.name` (not found) | `type(x).__getattr__(x, 'name')` | Dynamic attributes |
Some rows involve more than one method or a fallback. bool(x) tries __bool__ first and then __len__. If neither exists, the object is truthy. The in operator tries __contains__, then iteration, then __getitem__ with integer indexes starting at 0.
Lookup happens on the type
Implicit special method calls are looked up on the type of the object, not on the instance. This is the most important detail of the data model, and it causes real bugs.
class Greeter:
def __len__(self):
return 1
g = Greeter()
g.__len__ = lambda: 99
print(len(g)) # 1
print(g.__len__()) # 99Assigning __len__ on the instance has no effect on len(g). Python skips the instance and uses Greeter.__len__. Calling g.__len__() directly finds the instance attribute first, which is why the last line prints 99.
Python works this way for two reasons. The lookup is faster, because it skips the instance dictionary. It is also more predictable, because the behavior of len(x) can't change on a single object.
If you want per-instance behavior, define the method on the class and have it delegate to something stored on the instance.
class Sized:
def __init__(self, size_fn):
self._size_fn = size_fn
def __len__(self):
return self._size_fn()
print(len(Sized(lambda: 7))) # 7The flow of a binary operator
Binary operators have a two-step protocol. For a + b, Python first calls type(a).__add__(a, b). If that method returns the special value NotImplemented, Python then tries the reflected method on the right operand, type(b).__radd__(b, a). If that also returns NotImplemented, or doesn't exist, Python raises TypeError.
There is one exception to the order. If the right operand's type is a subclass of the left operand's type and overrides the reflected method, Python tries the right operand first. Later chapters cover reflected operators in full. For now, remember that returning NotImplemented is a request for Python to try another route, and that raising an exception ends the attempt immediately.
Calling special methods directly
Write len(x), not x.__len__(). The built-in function does more than call the method:
len()checks that the result is a non-negative integer and raises an error if it isn't.bool()checks that__bool__returned a realbool.- Operators try reflected methods and fallbacks that a direct call skips.
str()andrepr()check that the result is a string.
The usual exception is calling the parent class's method with super(), for example super().__init__() or super().__repr__().
What you get by default
Every class inherits from object, which supplies defaults for some special methods:
__repr__returns text such as<__main__.Box object at 0x...>.__eq__compares identity, so an object equals only itself.__hash__is derived from identity.__init__accepts no extra arguments if__new__isn't overridden.
Arithmetic, ordering, len(), iteration and the other operations have no default. Using them on an object that lacks the method gives a TypeError that names the operation.
try:
len(object())
except TypeError as e:
print(e) # object of type 'object' has no len()
try:
object() + object()
except TypeError as e:
print(e) # unsupported operand type(s) for +: 'object' and 'object'Common errors
- Setting a special method on an instance. It is ignored by operators and built-ins, as shown above.
- Misspelling the name.
__lenght__is a valid method name that Python never calls. Nothing warns you, solen(x)fails with aTypeErrorand the misspelled method just sits there. - Using the wrong signature.
__add__takesselfandother. A missing parameter shows up as a confusingTypeErrorat the point of use. - Raising
TypeErrorinstead of returningNotImplemented. A binary method that raises blocks the other operand from handling the request. ReturnNotImplementedfor unsupported types. - Inventing your own dunder names. Names with double underscores at both ends are reserved for Python. Use a single leading underscore for your own helpers.
Where the rest of the tutorial goes
The remaining chapters take one group of methods at a time. They cover text conversion, object creation, equality, ordering, truth value, arithmetic, containers, iteration, callables, context managers, attribute access and descriptors. The last chapter gives guidelines for deciding when overloading helps and when it makes code harder to read.
Each chapter follows the same pattern as this one. You write ordinary syntax. Python asks the type for a method. If the type has one, Python uses its result. If not, Python tries a fallback or raises TypeError.
Exercise
A class defines __len__, and you then run obj.__len__ = lambda: 5 on one instance. What do len(obj) and obj.__len__() return, and why?
Show answer
len(obj) returns the value from the class's __len__, because Python looks up special methods for built-in functions and operators on the type and ignores the instance dictionary. obj.__len__() returns 5, because an explicit attribute access finds the instance attribute first.
Exercise
What does Python do for a + b when type(a).__add__ returns NotImplemented and type(b) has no __radd__?
Show answer
It raises TypeError with an "unsupported operand type(s)" message. Python only tries __radd__ on the right operand after the left operand returns NotImplemented, and with no __radd__ to try, nothing is left to handle the operation.
Exercise
Why should you write len(x) instead of x.__len__() in normal code?
Show answer
The built-in function validates the result, for example that it is a non-negative integer, and follows the same lookup rules as the rest of the language. A direct call skips those checks and fallbacks, and it makes the code harder to read.