30.6 collections.abc: Built-in ABCs for Containers and Iterables

The collections.abc module provides a rich set of abstract base classes (ABCs) that define the core protocols for Python’s container and iterable types. These ABCs serve as both a formal specification and a mechanism for structural subtyping (duck typing), allowing you to check if an object conforms to a specific interface without requiring explicit inheritance. This is a cornerstone of Python’s philosophy, favoring protocols over rigid type hierarchies. The Core ABCs and Their Hierarchies The ABCs in collections.abc form a sophisticated inheritance hierarchy that mirrors the relationships between different container concepts. At the very top is the Container class, which requires the __contains__ method (in operator support). From there, the hierarchy branches into three main lines:

30.5 Using ABCs for isinstance() Checks

One of the most powerful applications of Abstract Base Classes (ABCs) is their ability to enforce a consistent interface across disparate classes, enabling reliable type checking. While duck typing is a cornerstone of Python’s philosophy, there are scenarios where explicitly checking for the presence of a specific protocol or capability is necessary and safer. The isinstance() function, when used with an ABC, transcends simple class inheritance checks; it verifies that an object adheres to the contract defined by the ABC, even if the object’s class doesn’t explicitly inherit from it.

30.4 Registering Virtual Subclasses

In addition to explicit inheritance, the abc module provides a mechanism for registering classes as “virtual subclasses” of an abstract base class (ABC). This allows a class to be considered a subclass of the ABC for the purposes of issubclass() and isinstance() checks without having to inherit from it directly. This is a powerful tool for integrating third-party or existing classes into a type hierarchy that you control, promoting structural subtyping (duck typing) while maintaining the formal guarantees of nominal subtyping.

30.3 Abstract Properties and Class Methods

Abstract base classes (ABCs) serve as blueprints for other classes, enforcing a contract that derived classes must implement specific methods and properties. While abstract methods are the most common mechanism for this, the abc module also provides decorators to define abstract properties and class methods, ensuring a consistent interface across hierarchies that includes more than just instance methods. Defining Abstract Properties An abstract property mandates that concrete subclasses must provide an implementation for that property. This is achieved using the @abstractmethod decorator in combination with the built-in @property decorator. The order of these decorators is critical: @abstractmethod must be the outermost decorator. This is because decorators are applied from the bottom up. The @property decorator creates a descriptor object, and the @abstractmethod then wraps that descriptor, marking it as abstract and ensuring the ABC’s __init__ method cannot complete unless it is overridden.

30.2 ABCMeta and the @abstractmethod Decorator

The Role of ABCMeta as the Metaclass At the heart of Python’s Abstract Base Class (ABC) implementation is the ABCMeta metaclass. A metaclass, often described as a “class of a class,” controls the construction of classes themselves. By inheriting from ABC (a helper class that simply uses ABCMeta as its metaclass) or by explicitly setting metaclass=ABCMeta, a class declares its intent to be an abstract base. The primary job of ABCMeta is to prevent instantiation of any class that still has unimplemented methods decorated with @abstractmethod. This enforcement occurs at the moment of instantiation, when the __new__ method of the metaclass is invoked. It checks the class’s __abstractmethods__ attribute, which is a set created automatically to contain the names of all abstract methods. If this set is not empty, instantiation is blocked by raising a TypeError.

30.1 Why Abstract Base Classes Exist

Abstract Base Classes (ABCs) represent a foundational concept in Python’s approach to object-oriented design, serving as a formal mechanism to define interfaces. Their existence is not to enable a feature that is otherwise impossible—duck typing allows for great flexibility without explicit inheritance—but to provide structure, clarity, and enforceability in large, complex codebases and frameworks. While Python’s dynamic nature famously adheres to the principle “if it walks like a duck and quacks like a duck, then it must be a duck,” this approach can sometimes lead to subtle bugs that are only discovered at runtime. ABCs act as a blueprint, explicitly stating what methods a subclass must implement, thereby making the contract between a framework and its plugins or between base and derived classes unambiguous and verifiable.

— joke —

...