Sub topic 9
The ABCs in collections.abc
This chapter assumes you can write classes with inheritance, know the special ("dunder") methods such as __len__ and __getitem__, and have read the earlier chapters on @abstractmethod and the instantiation check. The collections.abc module is where the standard library applies those ideas. It ships ready-made abstract base classes for iterables, sequences, mappings and sets.
What the module gives you
Each ABC in collections.abc does two jobs:
- Interface. It names a small set of abstract methods. A class that implements them counts as a member of that category.
- Mixin methods. It provides concrete methods built on top of the abstract ones. Subclassing the ABC gives you those methods without writing them.
For example, Mapping needs only __getitem__, __iter__ and __len__. From those three it builds __contains__, keys, items, values, get, __eq__ and __ne__. This is the template method pattern from the earlier chapter, applied to the standard library.
Import these classes from collections.abc. The old aliases directly in collections were removed in Python 3.10.
| ABC | Inherits from | Abstract methods | Mixin methods | Column |
|---|---|---|---|---|
| `Iterable` | none | `__iter__` | none | |
| `Iterator` | `Iterable` | `__next__` | `__iter__` | |
| `Sized` | none | `__len__` | none | |
| `Container` | none | `__contains__` | none | |
| `Collection` | `Sized`, `Iterable`, `Container` | `__len__`, `__iter__`, `__contains__` | none | |
| `Sequence` | `Reversible`, `Collection` | `__getitem__`, `__len__` | `__contains__`, `__iter__`, `__reversed__`, `index`, `count` | |
| `MutableSequence` | `Sequence` | `__getitem__`, `__setitem__`, `__delitem__`, `__len__`, `insert` | `append`, `extend`, `pop`, `remove`, `reverse`, `clear`, `__iadd__` | |
| `Mapping` | `Collection` | `__getitem__`, `__iter__`, `__len__` | `__contains__`, `keys`, `items`, `values`, `get`, `__eq__`, `__ne__` | |
| `MutableMapping` | `Mapping` | `__setitem__`, `__delitem__` plus the `Mapping` ones | `pop`, `popitem`, `clear`, `update`, `setdefault` | |
| `Set` | `Collection` | `__contains__`, `__iter__`, `__len__` | comparisons, `&`, `\ | `, `-`, `^`, `isdisjoint` |
| `MutableSet` | `Set` | `add`, `discard` plus the `Set` ones | `clear`, `pop`, `remove`, in-place operators |
The module also has Callable, Hashable, Generator, Awaitable, Reversible and others, but the rows above are the ones you subclass most often.
A read-only mapping from three methods
The Mapping ABC turns three methods into a full read-only dictionary interface.
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()))
print(config == {"host": "localhost", "port": 8080})The output is:
True
False
[('host', 'localhost'), ('port', 8080)]
Truein, get, items and == all come from Mapping. If you leave out __len__, Python raises TypeError when you create the object, just as in the earlier instantiation-check chapter.
A sequence from two methods
Sequence requires only __getitem__ and __len__. Everything else, including iteration, comes from them.
from collections.abc import Sequence
class Countdown(Sequence):
def __init__(self, start):
self._start = start
def __len__(self):
return self._start
def __getitem__(self, index):
if isinstance(index, slice):
return [self[i] for i in range(*index.indices(len(self)))]
if index < 0:
index += len(self)
if not 0 <= index < len(self):
raise IndexError(index)
return self._start - index
c = Countdown(5)
print(list(c))
print(3 in c)
print(c.index(2))
print(c.count(4))
print(list(reversed(c)))
print(c[1:3])The output is:
[5, 4, 3, 2, 1]
True
3
1
[1, 2, 3, 4, 5]
[4, 3]The mixin __iter__ calls self[0], self[1] and so on until IndexError. That is why __getitem__ must raise IndexError for out-of-range indexes. If it raises something else, iteration breaks.
The mixins are correct but not always fast. Sequence.__contains__ scans the whole sequence, so override it when your data structure can do better.
A mutable mapping and what update gives you
MutableMapping adds __setitem__ and __delitem__. In return you get pop, popitem, clear, update and setdefault. The class below normalizes keys to lowercase.
from collections.abc import MutableMapping
class LowerDict(MutableMapping):
def __init__(self, *args, **kwargs):
self._data = {}
self.update(*args, **kwargs)
def __getitem__(self, key):
return self._data[key.lower()]
def __setitem__(self, key, value):
self._data[key.lower()] = value
def __delitem__(self, key):
del self._data[key.lower()]
def __iter__(self):
return iter(self._data)
def __len__(self):
return len(self._data)
d = LowerDict({"Host": "a"}, Port=1)
print(d["HOST"])
print(d.pop("PORT"))
d.setdefault("Debug", False)
print(list(d))The output is:
a
1
['host', 'debug']Here update calls your __setitem__ for every pair, so the lowercase rule applies everywhere. A subclass of the built-in dict would not behave this way, because dict.update bypasses an overridden __setitem__. This is the main reason to prefer MutableMapping over subclassing dict when you customize storage.
A set from three methods
Set mixes in the comparison operators and the operators &, |, - and ^. They build their results with the classmethod _from_iterable, which by default calls cls(iterable). Your constructor must therefore accept a single iterable, or you must override _from_iterable.
from collections.abc import Set
class ListSet(Set):
def __init__(self, iterable=()):
self._items = list(dict.fromkeys(iterable))
def __contains__(self, value):
return value in self._items
def __iter__(self):
return iter(self._items)
def __len__(self):
return len(self._items)
a = ListSet([1, 2, 3])
b = ListSet([2, 3, 4])
print(sorted(a & b))
print(sorted(a | b))
print(a <= b)
print(a.isdisjoint(ListSet([9])))The output is:
[2, 3]
[1, 2, 3, 4]
False
TrueUsing these ABCs with isinstance
You use the ABCs for type checks as well as for inheritance. isinstance(x, Mapping) accepts dict, FrozenDict, LowerDict and any other mapping, including classes that never inherit from Mapping. Two mechanisms from earlier chapters make this work:
- The built-in containers are registered as virtual subclasses.
listis registered asMutableSequence, anddictasMutableMapping. They do not appear in each other's MRO. - The one-method ABCs (
Iterable,Sized,Container,Hashable,Callableand a few others) define__subclasshook__. Any class with the right method counts, with no inheritance or registration.
from collections.abc import Hashable, Iterable, Mapping, Sequence
print(isinstance("abc", Sequence))
print(isinstance(range(3), Sequence))
print(isinstance({1}, Sequence))
print(isinstance({}, Mapping))
print(isinstance(iter([]), Iterable))
print(isinstance(5, Iterable))
print(isinstance((1, 2), Hashable))
print(isinstance([], Hashable))The output is:
True
True
False
True
True
False
True
FalseThe subclass hook for Hashable only checks that __hash__ exists, so isinstance(([],), Hashable) is True, but hashing that tuple raises TypeError. Treat Hashable checks as a hint.
Pitfalls specific to collections.abc
- Strings are sequences.
isinstance("abc", Sequence)isTrue, as it is forbytes. Code that walks nested sequences recursively will never terminate on a string unless you excludestrandbytesfirst. - Define only what you need, but define all of it. If you forget one abstract method, you get
TypeError: Can't instantiate abstract class ... with abstract methods ...when you create an object. The message lists the missing names. - Mixins can be slow.
Sequence.index,Sequence.countandSequence.__contains__are linear scans.Mapping.__eq__copies items into dictionaries. Override the ones that matter on hot paths. MutableSequence.appendcallsinsert. If yourinsertis expensive at the end of the sequence,appendandextendwill be too.- Argument types in signatures. Annotate parameters with the least specific ABC that supports what you do:
Iterableif you loop once,Sequenceif you index,Mappingif you only read. Callers can then pass any matching type. Annotate return values with a concrete type when you can.
Choosing a base class
| You want | Subclass |
|---|---|
| A read-only, dict-like object | `Mapping` |
| A dict-like object with custom storage or key rules | `MutableMapping` |
| A list-like object with custom storage | `MutableSequence` |
| A custom lazy iterator | `Iterator`, or write a generator |
| To reuse the exact behavior of a built-in with small changes | `dict` or `list` directly, after checking that the methods you override are the ones the built-in actually calls |
Exercises
Exercise
A class subclasses Sequence and defines _getitem and len, but getitem never raises IndexError and simply returns self.items[index % len(self._items)]. What goes wrong when you write list(obj)?
Show answer
The mixin _iter calls obj[0], obj[1] and so on until IndexError is raised. Because the modulo makes every index valid, the iteration never ends and list(obj) grows without bound. getitem_ must raise IndexError for indexes outside range(len(self)).
Exercise
You write a MutableMapping subclass that stores its items in a plain dict called _data. Which five methods must you define, and which method gives you the ability to write obj.update({"a": 1})?
Show answer
Define _getitem, setitem, delitem, iter and len. The update method is a mixin supplied by MutableMapping, and it calls your setitem_ for each pair.