Sub topic 3
The ABCs in `collections.abc`
Assume you know classes, inheritance, decorators, properties, and exception handling. This chapter focuses on choosing and using existing abstract base classes (ABCs).
The ABCs in `collections.abc`
Python provides common ABCs for container behavior. For example, Mapping describes read-only mapping behavior. A subclass must implement __getitem__, __iter__, and __len__; Mapping supplies methods such as get, keys, items, and values.
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(config.get("port"))
print(list(config.items()))Other useful ABCs include Sequence, MutableMapping, Iterable, Iterator, and Callable. These ABCs combine required operations with reusable mixin methods.
Virtual subclasses with `register`
register() tells an ABC to treat an unrelated class as a subclass:
from collections.abc import Sized
class Report:
def __len__(self):
return 3
Sized.register(Report)
print(isinstance(Report(), Sized))
print(Sized in Report.__mro__) # FalseRegistration affects isinstance() and issubclass(), but it does not add methods or verify that the class actually works correctly.
Duck-typed checks with `__subclasshook__`
An ABC can customize subclass checks with __subclasshook__. It can accept classes that define a required method, even without inheritance or registration. Return NotImplemented when the custom rule does not apply so normal subclass checking can continue.
Choosing between an ABC and `typing.Protocol`
Use an ABC when you own a shared class hierarchy, need concrete methods, or want explicit registration. Use a Protocol when unrelated classes should match structurally because they expose the right methods. A protocol usually supports static type checkers; @runtime_checkable enables limited runtime checks.
Common pitfalls and design guidelines
- ABCs prevent instantiation of incomplete subclasses, not definition of those classes.
- Registered virtual subclasses are not checked for abstract methods.
- Keep
__subclasshook__simple. A method name alone may not prove compatible behavior. - Prefer a standard ABC such as
Mappingover inventing a similar one. - Do not force inheritance when a small protocol expresses the requirement better.
Exercise
Why does registering a class with an ABC not add the ABC to the class's method resolution order?
Show answer
Registration changes ABC instance and subclass checks, but it does not create inheritance or copy methods.