Select Container Interfaces with collections.abc
Core idea
The abstract base classes in collections.abc describe supported operations. Choose Mapping for key lookup, Sequence for positional access, or Iterable for iteration. MutableMapping and MutableSequence describe additional modification operations. Runtime isinstance checks recognize subclasses, registered implementations and some simple structural interfaces; they are not complete semantic validation.
from collections import ChainMapfrom collections.abc import Mappingdef read_limit(settings): if not isinstance(settings, Mapping): raise TypeError("mapping required") return settings["limit"]print(read_limit({"limit": 4}))print(read_limit(ChainMap({}, {"limit": 7})))Both objects meet the Mapping interface; the function does not require dict specifically.
Compare mutable interfaces
from collections.abc import Sequence, MutableSequenceprint(isinstance((1, 2), Sequence))print(isinstance((1, 2), MutableSequence))print(isinstance([1, 2], MutableSequence))A tuple supports sequence reading, but not the mutable sequence interface.
Implement a minimal sequence
from collections.abc import Sequenceclass Samples(Sequence): def __init__(self, values): self.values = tuple(values) def __len__(self): return len(self.values) def __getitem__(self, index): return self.values[index]s = Samples([3, 5, 3])print(s.count(3), list(s))Implementing the required methods lets the class inherit count and iteration behavior.
Common mistake
An object using only the legacy getitem iteration protocol may pass iter(obj) but fail isinstance(obj, Iterable). Also, merely registering a virtual subclass does not provide missing methods.
Practice
Write a function that only reads mapping keys; test it with dict and ChainMap. Then test a list and a tuple against MutableSequence.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Container interfaces
Check your understanding of collections abcs.
What is printed?
from collections import ChainMapfrom collections.abc import Mapping, Sequenceprint(isinstance(ChainMap(),Mapping),isinstance(ChainMap(),Sequence))What is printed?
from collections.abc import MutableSequenceprint(isinstance([],MutableSequence),isinstance((),MutableSequence))What is printed?
from collections.abc import Iterableclass Legacy: def __getitem__(self, i): if i == 0: return 8 raise IndexErrorx = Legacy()print(isinstance(x, Iterable), list(x))Which interface best expresses read-only lookup by key?