Making Python Objects Feel Built-In: Special Methods and the Data Model
This article explains how the Python data model lets custom classes support len(), indexing, iteration, printing and operators through special methods, and describes the pitfalls of implementing them.
The present article addresses the Python data model, the set of rules that determines how the interpreter applies its built-in operations to any object. The problem it solves becomes evident as soon as a custom class is written: an instance of that class rejects len(), square brackets and the + operator, although a list accepts all of them. The data model removes that difference, since it defines which methods an object must provide for each operation to work on it. This means that a class written by the programmer can behave like a built-in type without inheriting from one, which is the magic that the following sections examine.
Special Methods: The Contract with the Interpreter
Special methods are methods whose names begin and end with a double underscore, such as __init__ or __len__, and for that reason they are often called "dunder" methods. The interpreter calls them implicitly: the expression len(obj) is resolved by calling __len__, and obj[0] by calling __getitem__. A class that defines neither method produces the following errors.
class Playlist:
def __init__(self, tracks):
self._tracks = list(tracks)
playlist = Playlist(["Intro", "Overture"])
for operation in (len, lambda p: p[0]):
try:
operation(playlist)
except TypeError as error:
print(error)
# Output: object of type 'Playlist' has no len()
# Output: 'Playlist' object is not subscriptable
The interpreter does not look for these methods on the instance, but on its type. As examined in the article devoted to metaclasses, a class is itself an object, and the expression len(playlist) is in fact resolved as type(playlist).__len__(playlist). This detail, which the reference documentation describes under the name of special method lookup, explains one of the pitfalls described later in this article.
Building a Collection with __len__ and __getitem__
The present section turns the class Playlist into a collection by adding two methods, each of which delegates the work to the internal list. The following example shows the complete class and the operations that it supports from that moment.
class Playlist:
def __init__(self, tracks):
self._tracks = list(tracks)
def __len__(self):
return len(self._tracks)
def __getitem__(self, position):
return self._tracks[position]
playlist = Playlist(["Intro", "Overture", "Interlude", "Finale"])
print(len(playlist)) # Output: 4
print(playlist[0], playlist[-1]) # Output: Intro Finale
print(playlist[1:3]) # Output: ['Overture', 'Interlude']
print(list(playlist)) # Output: ['Intro', 'Overture', 'Interlude', 'Finale']
print("Finale" in playlist) # Output: True
print(list(reversed(playlist))) # Output: ['Finale', 'Interlude', 'Overture', 'Intro']
print(bool(Playlist([]))) # Output: False
Two methods have produced seven behaviours, and the reasons deserve a precise account. Indexing with negative numbers and slicing work because __getitem__ passes its argument, an integer or a slice object, to the internal list. Iteration and the operator in work because iter() falls back on the old sequence protocol when a class lacks __iter__: it calls __getitem__ with 0, 1, 2 and so on until an IndexError is raised. Likewise, reversed() combines __len__ with __getitem__, and bool() falls back on __len__ when __bool__ is not defined, so that an empty playlist is false.
The interpreter, in all these cases, never asks whether Playlist is a list; it only checks that the methods it needs are present. An old hermit of a distant galaxy relies on the same principle when he waves his hand at a checkpoint and declares "these aren't the droids you're looking for", because the guards inspect only what is presented to them and not the identity behind it. This is the duck typing on which the whole data model rests.
Representation: __repr__ and __str__
Every object has two textual forms, and the data model assigns a different method to each one. The method __repr__ produces an unambiguous representation, intended for developers and used by the interactive console and by containers, whereas __str__ produces the readable form that print() and str() display.
class Track:
def __init__(self, title, seconds):
self.title = title
self.seconds = seconds
def __repr__(self):
return f"Track({self.title!r}, {self.seconds})"
def __str__(self):
minutes, seconds = divmod(self.seconds, 60)
return f"{self.title} ({minutes}:{seconds:02d})"
track = Track("Overture", 245)
print(repr(track)) # Output: Track('Overture', 245)
print(track) # Output: Overture (4:05)
print([track]) # Output: [Track('Overture', 245)]
The last line shows that a list displays its elements with __repr__, not with __str__. Consequently, __repr__ is the method that should be implemented first, since str() falls back on it when __str__ is absent, whereas the opposite fallback does not exist.
Operators and Equality
In addition to collections and text, the data model governs operators. The operator == calls __eq__, and + calls __add__; when either method receives an operand that it does not support, it must return the singleton NotImplemented instead of raising an exception, so that Python can try the reflected method of the other operand before reporting the error.
class Playlist:
def __init__(self, tracks):
self._tracks = list(tracks)
def __repr__(self):
return f"Playlist({self._tracks!r})"
def __eq__(self, other):
if not isinstance(other, Playlist):
return NotImplemented
return self._tracks == other._tracks
def __add__(self, other):
if not isinstance(other, Playlist):
return NotImplemented
return Playlist(self._tracks + other._tracks)
morning = Playlist(["Intro"])
evening = Playlist(["Finale"])
print(morning + evening) # Output: Playlist(['Intro', 'Finale'])
print(morning == Playlist(["Intro"])) # Output: True
print(morning == ["Intro"]) # Output: False
try:
morning + ["Finale"]
except TypeError as error:
print(error) # Output: unsupported operand type(s) for +: 'Playlist' and 'list'
print(Playlist.__hash__) # Output: None
The comparison with a list returns False rather than an error, because after NotImplemented the interpreter falls back on identity for ==. The addition with a list, on the other hand, fails with an informative message that Python composes by itself. The last line reveals a side effect that the next section examines in detail.
Pitfalls of Special Methods
This section identifies the errors that appear most often when special methods are implemented. Four pitfalls are distinguished, which are the following:
- Lookup on the type. A special method assigned to an instance is ignored by the operation that should use it, because the interpreter looks it up on the class.
- Equality without hashing. A class that defines
__eq__without__hash__receives__hash__ = None, so its instances can no longer be keys of a dictionary or elements of a set. - Iterable but not recognized as such. A class that relies on the sequence-protocol fallback can be traversed with
for, yetisinstance(obj, collections.abc.Iterable)returnsFalse, because that check looks only for__iter__. - Slices of the wrong type. A
__getitem__that delegates to a list returns alistwhen it receives a slice, not an instance of the custom class.
The first, third and fourth pitfalls are reproduced in the following example.
from collections.abc import Iterable
class Playlist:
def __init__(self, tracks):
self._tracks = list(tracks)
def __len__(self):
return len(self._tracks)
def __getitem__(self, position):
return self._tracks[position]
playlist = Playlist(["Intro", "Finale"])
playlist.__len__ = lambda: 99
print(len(playlist)) # Output: 2 (the instance attribute is ignored)
print(isinstance(playlist, Iterable)) # Output: False
print(type(playlist[0:1]).__name__) # Output: list
The second pitfall was already visible in the previous section, where Playlist.__hash__ printed None. When instances must remain hashable, __hash__ has to be defined explicitly from the same fields that __eq__ compares, and those fields should not change while the object is stored in a set or used as a key.
Inheriting the Rest from collections.abc.Sequence
The third and fourth pitfalls share a solution that the standard library already provides. A class that inherits from collections.abc.Sequence and implements __len__ and __getitem__ receives __contains__, __iter__, __reversed__, index and count without further code, and it is recognized as both a sequence and an iterable.
from collections.abc import Iterable, Sequence
class Playlist(Sequence):
def __init__(self, tracks):
self._tracks = list(tracks)
def __len__(self):
return len(self._tracks)
def __getitem__(self, position):
if isinstance(position, slice):
return Playlist(self._tracks[position])
return self._tracks[position]
playlist = Playlist(["Intro", "Overture", "Finale", "Intro"])
print(isinstance(playlist, Iterable)) # Output: True
print(playlist.index("Finale")) # Output: 2
print(playlist.count("Intro")) # Output: 2
print(type(playlist[0:2]).__name__) # Output: Playlist
The branch for slice objects keeps slices inside the custom type, and the base class supplies the remaining methods. For classes that mainly store data, the decorator @dataclass, available since Python 3.7, generates __init__, __repr__ and __eq__ in the same spirit. The choice of methods therefore depends on the role of the class, as the following table summarizes.
| The class should | Methods to implement |
|---|---|
Report its size and support bool() |
__len__ (and __bool__ if emptiness is not the criterion) |
| Support indexing, slicing and iteration | __getitem__, preferably within collections.abc.Sequence |
| Display itself clearly | __repr__ first, __str__ when a readable form differs |
| Be compared and used in sets or dictionaries | __eq__ together with __hash__ |
| Support arithmetic operators | __add__ and its relatives, returning NotImplemented for unsupported operands |
Conclusion
It is concluded that the data model is the contract through which a class written by the programmer obtains the same treatment as the built-in types, and that the interpreter honours that contract by looking up special methods on the type of each object. This secret weapon explains why two methods are enough to make a class indexable, iterable and reversible, and why a single __eq__ can silently make it unhashable. Its magic, however, is precise rather than unlimited: the fallbacks of the sequence protocol are not recognized by every check, and the abstract base classes of collections.abc remain the most reliable way to declare what a class is. The iterator protocol, formed by __iter__ and __next__, is the natural continuation of this topic, since it replaces the fallback described here with an explicit mechanism, and it is developed in a future article of this series.