Sub topic 11
Building container-like classes
This chapter assumes you can write classes with instance attributes and methods, and that you know how list, dict and tuple behave. A container is an object that holds other objects and answers questions such as "how many?", "what is at position 2?" and "is this inside?". You can make your own classes answer those questions with the same syntax the built-in types use.
Syntax that maps to container methods
Python does not check whether your class inherits from list. It looks up special methods on the object's type, so any class that defines them works with the matching syntax.
| Syntax | Method called | Typical job |
|---|---|---|
| `len(obj)` | `__len__` | Return the number of items as an `int` |
| `obj[key]` | `__getitem__` | Read an item by index, slice, or key |
| `obj[key] = value` | `__setitem__` | Replace or add an item |
| `del obj[key]` | `__delitem__` | Remove an item |
| `item in obj` | `__contains__` | Membership test |
Most classes need only __len__ and __getitem__. Python builds several other behaviors from those two.
A read-only sequence
The Playlist class below defines __len__, __getitem__ and __contains__.
class Playlist:
def __init__(self, songs):
self._songs = list(songs)
def __len__(self):
return len(self._songs)
def __getitem__(self, index):
return self._songs[index]
def __contains__(self, song):
return song in self._songs
p = Playlist(['Intro', 'Verse', 'Outro'])
print(len(p)) # 3
print(p[0]) # Intro
print(p[1:]) # ['Verse', 'Outro']
print('Verse' in p) # True
for song in p: # iteration works through __getitem__
print(song)
print(list(reversed(p))) # ['Outro', 'Verse', 'Intro']Several behaviors here come for free:
- Iteration. If a class has no
__iter__but has__getitem__,iter()falls back to callingobj[0],obj[1]and so on. It stops whenIndexErroris raised. The list insidePlaylistraises that error at the end, so the loop ends cleanly. - Reversal.
reversed()needs__len__and__getitem__. It asks for the length, then reads from the last index down to 0. - Truthiness. If a class has no
__bool__, Python calls__len__, and an object of length 0 is falsy. An emptyPlaylistis thereforeFalsein aniftest. - Delegation. Because
__getitem__passesindexstraight to a list, negative indexes and slices work without extra code.
Slices are objects
The expression p[1:] calls p.__getitem__(slice(1, None, None)). The argument is a slice object with start, stop and step attributes. In Playlist, the inner list handles it, so a slice returns a plain list. Built-in sequences return their own type, so Playlist[1:] arguably should return a Playlist. Handling this means checking the argument type.
A mutable sequence
Add __setitem__ and __delitem__ to allow assignment and deletion. The version below also returns a Playlist from slices.
class Playlist:
def __init__(self, songs=()):
self._songs = list(songs)
def __repr__(self):
return f'Playlist({self._songs!r})'
def __len__(self):
return len(self._songs)
def __getitem__(self, index):
if isinstance(index, slice):
return Playlist(self._songs[index])
return self._songs[index]
def __setitem__(self, index, value):
self._songs[index] = value
def __delitem__(self, index):
del self._songs[index]
p = Playlist(['Intro', 'Verse', 'Outro'])
print(p[1:]) # Playlist(['Verse', 'Outro'])
p[0] = 'Opening'
del p[1]
print(p) # Playlist(['Opening', 'Outro'])
p[0:1] = ['A', 'B'] # slice assignment passes a slice and an iterable
print(p) # Playlist(['A', 'B', 'Outro'])
print(bool(Playlist())) # FalseSlice assignment can change the length of the container, which is why this class passes the slice and the new value straight to the list. A class that stores data in a fixed-size structure would need to reject such assignments with a ValueError or TypeError.
Keys that are not integers
__getitem__ receives whatever you put between the brackets. For obj[2, 3], the argument is the tuple (2, 3). That makes it easy to build grids, tables and mapping-like classes.
class SparseGrid:
def __init__(self, default=0):
self._cells = {}
self.default = default
def __getitem__(self, key):
row, col = key
return self._cells.get((row, col), self.default)
def __setitem__(self, key, value):
row, col = key
self._cells[(row, col)] = value
def __contains__(self, key):
return tuple(key) in self._cells
def __len__(self):
return len(self._cells)
g = SparseGrid()
g[2, 3] = 7
print(g[2, 3]) # 7
print(g[0, 0]) # 0
print((2, 3) in g) # True
print((0, 0) in g) # False
print(len(g)) # 1Here len() counts only cells that were set, and in checks only stored cells. g[0, 0] still returns the default. Document choices like this, because users may expect in and indexing to agree.
Choosing the right exception
Callers and Python itself rely on specific exceptions.
- Sequence-like classes raise
IndexErrorfor an out-of-range integer index. The fallback iteration protocol depends on this. - Mapping-like classes raise
KeyErrorfor a missing key. - Wrong key types usually raise
TypeError, such as a string used as a sequence index.
If you raise the wrong exception, the fallback iteration may never stop or may crash with a confusing message.
Common mistakes
- Defining
__getitem__but returningNonefor missing items. The iteration fallback then never reaches anIndexError, so aforloop runs forever. - Implementing
__len__that returns a non-integer.len()raisesTypeErrorfor floats, and a negative result raisesValueError. - Making
__contains__disagree with iteration.x in objandx in list(obj)should give the same answer. - Forgetting that
__len__affects truthiness. An object with__len__returning 0 is falsy. If an empty container should still count as true, define__bool__. - Ignoring negative indexes. If you compute positions yourself rather than delegating to a list, handle
-1deliberately.
Sequences can also be built on collections.abc.Sequence or MutableSequence. You supply __getitem__ and __len__, and the base class adds __contains__, __iter__, __reversed__, index and count. This is worth using once your container grows past a few methods.
Exercise
A class defines only __len__ and __getitem__, where __getitem__ returns self._items[index] for a list _items. Name three built-in behaviors that work on instances of this class without any other methods, and say what makes the for loop stop.
Show answer
The class supports for loops, reversed(), and in tests, and an empty instance is falsy through __len__. Python's fallback iteration calls __getitem__ with 0, 1, 2 and so on. The loop stops when the list raises IndexError for an index past the end.
Exercise
What does g.__getitem__ receive when you write g[1, 2], and what does it receive for g[1:3]?
Show answer
For g[1, 2] it receives the tuple (1, 2). For g[1:3] it receives slice(1, 3, None).