Sub topic 9
The ABCs in collections.abc
This chapter assumes you can write classes with inheritance, know how @abstractmethod blocks instantiation, and have seen isinstance with ABCs. Here you will use the ready-made ABCs in collections.abc to build container classes with little code.
Abstract methods and mixin methods
Each ABC in collections.abc has two kinds of methods:
- Abstract methods are the small core you must write. Without them, instantiation raises
TypeError. - Mixin methods are concrete methods the ABC builds on top of that core. You get them by inheriting.
This is the template method idea from earlier, applied to Python's own container protocols.
| ABC | You implement | You get for free |
|---|---|---|
| `Sequence` | `__getitem__`, `__len__` | `__contains__`, `__iter__`, `__reversed__`, `index`, `count` |
| `Mapping` | `__getitem__`, `__iter__`, `__len__` | `__contains__`, `keys`, `items`, `values`, `get`, `==` |
| `MutableMapping` | the `Mapping` methods plus `__setitem__`, `__delitem__` | `pop`, `popitem`, `clear`, `update`, `setdefault` |
| `MutableSequence` | `__getitem__`, `__setitem__`, `__delitem__`, `__len__`, `insert` | `append`, `extend`, `reverse`, `pop`, `remove`, `+=` |
A read-only mapping
FrozenDict implements only the three required methods. Everything else comes from Mapping.
from collections.abc import Mapping
class FrozenDict(Mapping):
def __init__(self, data):
self._data = dict(data)
def __getitem__(self, key):
return self._data[key]
def __iter__(self):
return iter(self._data)
def __len__(self):
return len(self._data)
config = FrozenDict({"host": "localhost", "port": 8080})
print("host" in config)
print(config.get("debug", False))
print(list(config.items()))The output is True, False, and [('host', 'localhost'), ('port', 8080)]. The class has no __setitem__, so config["x"] = 1 raises TypeError. That is the behavior you want from a read-only type.
A sequence with two methods
Sequence needs only __getitem__ and __len__.
from collections.abc import Sequence
class Deck(Sequence):
def __init__(self, cards):
self._cards = list(cards)
def __getitem__(self, index):
return self._cards[index]
def __len__(self):
return len(self._cards)
deck = Deck(["A", "K", "Q"])
print("K" in deck)
print(deck.index("Q"))
print(list(reversed(deck)))
print(deck[0:2])The output is True, 2, ['Q', 'K', 'A'], and ['A', 'K']. Slicing works because __getitem__ passes the slice to the inner list. If you want slices to return a Deck, handle slice objects yourself.
How the hierarchy fits together
Collection itself combines three one-method ABCs: Sized, Iterable and Container. Subclassing a mutable ABC adds abstract methods, so a class that inherits MutableMapping must also write __setitem__ and __delitem__.
Using the ABCs for type checks
Prefer collections.abc in isinstance checks over concrete types. A check like isinstance(x, Mapping) accepts dict, FrozenDict, and any other mapping. dict and list are registered as virtual subclasses of MutableMapping and MutableSequence.
from collections.abc import Iterable, Mapping, Sequence
print(isinstance({}, Mapping))
print(isinstance([], Iterable))
print(isinstance("abc", Sequence))All three lines print True. The last one is a common trap: a str is a Sequence, so code that means "a list of names" can accept a single string by accident.
Common mistakes
- Missing one core method. Leaving out
__len__on aMappingsubclass makes instantiation fail withTypeError, listing the missing names. - Slow mixins. Mixins use only the core methods. The inherited
Sequence.__contains__scans item by item, so override it if you have a faster lookup. - Detecting iterables.
isinstance(x, Iterable)checks for__iter__. It misses old-style objects that iterate only through__getitem__. Callingiter(x)is the reliable test. - Subclassing
dictinstead. Inheriting fromdictcan bypass your overrides, because built-in methods such asupdateoften skip__setitem__.MutableMappingroutes everything through your methods.
Exercise
A class inherits from MutableMapping and defines __getitem__, __setitem__, __iter__ and __len__. Why does MutableMapping still raise TypeError when you instantiate it, and which method is missing?
Show answer
MutableMapping also requires __delitem__. Without it, Python lists __delitem__ as an unimplemented abstract method and refuses to create the object. Adding __delitem__ fixes it, and you then get pop, popitem, clear, update and setdefault as mixins.