Sub topic 11
Building container-like classes
This chapter assumes you can define classes, know how list, dict and tuple behave, and have used for loops. You will make your own class act like a sequence by adding a few special methods.
The container protocol
Python does not require you to inherit from list. Built-in functions and syntax look for special methods on the object's type. If the method exists, the feature works.
| Syntax | Method called |
|---|---|
| `len(obj)` | `__len__` |
| `obj[i]`, `obj[1:]` | `__getitem__` |
| `obj[i] = v` | `__setitem__` |
| `del obj[i]` | `__delitem__` |
| `x in obj` | `__contains__` |
A read-only playlist
Start with __len__ and __getitem__.
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']__getitem__ passes its argument straight to the inner list. An integer returns one song, and a slice such as 1: returns a list. Because the list does the work, negative indexes and IndexError for out-of-range positions also work.
Why iteration and reversed() work
You did not write __iter__, yet for works. If a class has no __iter__, Python tries __getitem__ with 0, 1, 2 and so on, until it gets IndexError. The reversed() function needs __len__ and __getitem__ and counts down from the last index.
Why define __contains__
Without __contains__, in falls back to iteration and compares each item. Defining it is optional here, but it lets you use a faster check. For example, a class backed by a set can test membership in constant time.
Making it writable
Add __setitem__ and __delitem__ to support assignment and deletion.
class MutablePlaylist:
def __init__(self, songs=()):
self._songs = list(songs)
def __len__(self):
return len(self._songs)
def __getitem__(self, index):
return self._songs[index]
def __setitem__(self, index, song):
self._songs[index] = song
def __delitem__(self, index):
del self._songs[index]
m = MutablePlaylist(['A', 'B', 'C'])
m[1] = 'X'
del m[0]
print(len(m), m[0], m[1]) # 2 X CCommon errors
- Returning the wrong type from a slice.
Playlistreturns a plainlistfor slices. If you want aPlaylist, checkisinstance(index, slice)and wrap the result. - Raising the wrong exception. Sequence iteration stops on
IndexError. AKeyErroris correct for mapping-like classes, but it will break the fallback iteration for sequences. - Inconsistent
__len__.len()must return a non-negative integer. A class with__len__returning 0 is also falsy in aniftest. - Missing
__setitem__. Assigningp[0] = 'x'onPlaylistraisesTypeError: 'Playlist' object does not support item assignment.
Exercise
You write a class with only __len__ and __getitem__, where __getitem__ delegates to an internal list. Name two things besides len() and indexing that now work, and say why.
Show answer
A for loop and reversed() both work, and so does the in operator. A for loop and in use the fallback of calling __getitem__ with 0, 1, 2 and so on until IndexError. reversed() uses __len__ to find the last index and __getitem__ to read each item backwards.