Lib/_collections_abc.py
Source:
cpython 3.14 @ ab2d84fe1023/Lib/_collections_abc.py
Lib/_collections_abc.py defines the abstract base classes (ABCs) for Python's container types. These ABCs are re-exported as collections.abc.*. Each ABC uses __subclasshook__ for virtual subclass registration (so a class implementing the required methods is considered a subclass even without explicit inheritance) and provides mixin methods built from the abstract ones.
Map
| Lines | Symbol | Role |
|---|---|---|
| 1-80 | ABCMeta, helper | Metaclass import; _check_methods |
| 81-200 | Hashable, Iterable, Iterator, Reversible | Primitive ABCs |
| 201-400 | Sized, Container, Collection | Size/containment ABCs |
| 401-600 | Sequence, MutableSequence | Ordered sequence ABCs with mixin methods |
| 601-750 | Mapping, MutableMapping | Dict-like ABCs |
| 751-900 | Set, MutableSet | Set ABCs with set-arithmetic mixins |
| 901-1000 | ByteString, Buffer, registration | Bytes-like ABCs; virtual registrations |
Reading
subclasshook for duck typing
Iterable.__subclasshook__ returns True if the class has an __iter__ method, making any class with __iter__ a virtual subclass of Iterable without explicit inheritance. _check_methods(C, *methods) is the helper that walks the MRO checking for the presence of each method name.
# CPython: Lib/_collections_abc.py:81 Iterable.__subclasshook__
class Iterable(metaclass=ABCMeta):
@abstractmethod
def __iter__(self): ...
@classmethod
def __subclasshook__(cls, C):
if cls is Iterable:
return _check_methods(C, '__iter__')
return NotImplemented
MutableSequence mixin methods
MutableSequence declares __getitem__, __setitem__, __delitem__, __len__, and insert as abstract, then provides concrete implementations of append, clear, reverse, extend, pop, __iadd__, and __contains__ in terms of the abstract methods.
# CPython: Lib/_collections_abc.py:401 MutableSequence.append
class MutableSequence(Sequence):
def append(self, value):
self.insert(len(self), value)
def pop(self, index=-1):
v = self[index]
del self[index]
return v
Set arithmetic mixins
Set provides __and__, __or__, __xor__, __sub__, and their reflected variants as mixin methods built from __contains__, __iter__, and __len__. MutableSet adds add, discard, and __ior__, __iand__, __ixor__, __isub__.
gopy notes
Not yet ported. In Go, interface types serve the same role as ABCs; there is no virtual subclass registration mechanism. A faithful port would use Go interfaces for the protocol checks and ignore __subclasshook__ since Go's type system does not need it.