Python Abstract Base Classes: Interfaces That Python Enforces
This article explains how the abc module declares abstract methods and properties, when the interpreter enforces them, how virtual subclasses and collections.abc extend the mechanism, and how abstract base classes compare with protocols.
A family of related classes, such as several exporters that write the same report in different formats, works only if every member provides the same methods. In plain Python that requirement is a convention, and a subclass that forgets one method fails only when the missing method is finally called. The module abc turns the convention into a rule: an abstract base class declares the methods that its subclasses must implement, and it refuses to create instances of any subclass that leaves one of them out. The present article examines how abstract methods and properties are declared, when the check takes place, how virtual subclasses and __subclasshook__ extend the mechanism, how the ABCs of collections.abc supply ready-made interfaces, and how abstract base classes compare with protocols. A contract that the interpreter enforces is the secret weapon of this module.
Declaring an Abstract Base Class
A class becomes abstract when it inherits from abc.ABC and marks at least one method with @abstractmethod. The class can still contain ordinary methods, which subclasses inherit, and an abstract method can carry a default implementation that subclasses reach through super(). Combined with property, classmethod or staticmethod, the decorator abstractmethod must be the innermost one.
from abc import ABC, abstractmethod
class Exporter(ABC):
@property
@abstractmethod
def extension(self): ...
@abstractmethod
def render(self, rows):
return " | ".join(rows)
def export(self, rows):
return f"[{self.extension}] {self.render(rows)}"
class CsvExporter(Exporter):
extension = "csv"
def render(self, rows):
return ",".join(rows)
class TextExporter(Exporter):
@property
def extension(self):
return "txt"
def render(self, rows):
return super().render(rows).upper()
print(sorted(Exporter.__abstractmethods__)) # Output: ['extension', 'render']
print(CsvExporter().export(["ada", "grace"])) # Output: [csv] ada,grace
print(TextExporter().export(["ada", "grace"])) # Output: [txt] ADA | GRACE
The attribute __abstractmethods__ lists what a concrete subclass must provide, here one property and one method. CsvExporter satisfies the property with a plain class attribute, and TextExporter reuses the default implementation of render through super(), which shows that "abstract" in Python means "must be overridden", not "has no body". The ordinary method export is written once in the base class and works for every subclass. The helper class ABC, available since Python 3.4, is only a shortcut for metaclass=ABCMeta, the metaclass that records abstract methods, a mechanism described in the article devoted to metaclasses.
When the Contract Is Checked
The check takes place when a class is instantiated, not when it is defined. A subclass that omits an abstract member is created without complaint, and the error appears at the first attempt to build an object from it.
from abc import ABC, abstractmethod
class Exporter(ABC):
@abstractmethod
def render(self, rows): ...
@classmethod
def describe(cls):
return f"{cls.__name__} exporter"
class JsonExporter(Exporter):
def dump(self, rows):
return str(rows)
print(JsonExporter.describe()) # Output: JsonExporter exporter
try:
JsonExporter()
except TypeError as error:
print(error)
# Output (CPython 3.12): Can't instantiate abstract class JsonExporter without an implementation for abstract method 'render'
The incomplete class exists, and its class methods can even be called; only instantiation is blocked. The protection is therefore earlier than a missing-method error at the moment of the call, but later than a static type checker, which reports the same omission before the program runs. The wording of the message has changed between versions, so code should not depend on it.
Virtual Subclasses and __subclasshook__
Inheritance is not the only way to belong to an ABC. The method register declares an existing class, for example one from a third-party library, as a virtual subclass, and the class method __subclasshook__ lets an ABC recognize classes by their methods, which is how the one-method interfaces of collections.abc work.
from abc import ABC, abstractmethod
from collections.abc import Iterable, Sequence, Sized
class Exporter(ABC):
@abstractmethod
def render(self, rows): ...
def export(self, rows):
return self.render(rows)
@Exporter.register
class LegacyWriter:
pass
print(issubclass(LegacyWriter, Exporter)) # Output: True
try:
LegacyWriter().export(["ada"])
except AttributeError as error:
print(error) # Output: 'LegacyWriter' object has no attribute 'export'
class Bag:
def __init__(self, *items):
self.items = list(items)
def __iter__(self):
return iter(self.items)
def __len__(self):
return len(self.items)
bag = Bag(1, 2)
print(isinstance(bag, Iterable), isinstance(bag, Sized), isinstance(bag, Sequence))
# Output: True True False
Registration is a promise that the interpreter does not verify: LegacyWriter passes issubclass although it implements nothing, and it inherits no method from the ABC, so export does not exist on it. Bag, on the other hand, was never registered, yet Iterable and Sized recognize it through their __subclasshook__, which only looks for __iter__ and __len__. Sequence does not, because a method such as __getitem__ cannot distinguish a sequence from a mapping, so richer interfaces require explicit subclassing or registration.
Interfaces with Mixin Methods: collections.abc
Subclassing an ABC of collections.abc gives more than a check: the ABC supplies mixin methods built on top of the abstract ones. A sequence needs only __getitem__ and __len__, and Sequence derives the rest.
from collections.abc import Sequence
class Squares(Sequence):
def __init__(self, size):
self.size = size
def __len__(self):
return self.size
def __getitem__(self, index):
if not 0 <= index < self.size:
raise IndexError(index)
return index * index
squares = Squares(5)
print(list(squares)) # Output: [0, 1, 4, 9, 16]
print(9 in squares, squares.index(16), squares.count(4)) # Output: True 4 1
print(list(reversed(squares))) # Output: [16, 9, 4, 1, 0]
Membership, index, count, iteration and reversed are all provided by Sequence, so two methods produce a complete read-only sequence. The attribute is named size rather than count on purpose, since an instance attribute called count would hide the mixin method of the same name. The same idea, seen from the side of the special methods, is developed in the article devoted to the data model. The mixin methods are generic implementations; a class that can answer in or index faster, for example through a dictionary, should override them.
It Is a Trap: Pitfalls of Abstract Base Classes
The mechanism of ABCs is simple, but its guarantees are narrower than the word "contract" suggests. Five pitfalls are distinguished, which are the following:
- Late detection. The check runs at instantiation; an incomplete subclass is discovered only when the first object is created, which may happen far from the class definition.
- Names, not signatures. The ABC verifies that a method with the right name exists, not that its parameters or return type match the abstract declaration.
- Unverified registration.
registeraccepts any class, and virtual subclasses receive neither the checks nor the methods of the ABC. - Metaclass conflicts.
ABCbrings the metaclassABCMeta, so combining it with a class that uses another metaclass raisesTypeErrorunless a common metaclass is defined. - Deprecated helpers.
abstractproperty,abstractclassmethodandabstractstaticmethodhave been deprecated since Python 3.3; the combination ofproperty,classmethodorstaticmethodwithabstractmethodreplaces them.
The fourth pitfall is reproduced in the following example.
from abc import ABC
class PluginMeta(type):
pass
class Plugin(metaclass=PluginMeta):
pass
try:
class AbstractPlugin(Plugin, ABC):
pass
except TypeError as error:
print(error)
# Output (CPython 3.12): metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
The class AbstractPlugin would need a metaclass derived from both PluginMeta and ABCMeta, and Python cannot choose one by itself. Defining class PluginABCMeta(PluginMeta, ABCMeta) and using it explicitly resolves the conflict.
Choosing Between ABCs and Protocols
Consequently, an abstract base class is appropriate when the classes of a family share code and must be checked at construction, while a protocol, as shown in the article devoted to advanced type hints, describes an interface without requiring any inheritance. The following table summarizes the choice.
| Need | Recommended construct |
|---|---|
| Family of classes that share code and must implement certain methods | Subclass of abc.ABC with @abstractmethod |
| Full container interface from a few methods | Subclass of collections.abc.Sequence, Mapping or Set |
| Check whether an object is iterable, sized or callable | isinstance with collections.abc.Iterable, Sized or Callable |
| Declare an existing class as compatible without changing it | ABC.register, with manual verification |
| Accept any object with the right methods, checked before running | typing.Protocol with a static type checker |
| Small scripts with a single implementation | No ABC; an ordinary class is enough |
Conclusion
It is concluded that abstract base classes convert an informal interface into a rule that the interpreter enforces at instantiation, and that, through collections.abc, they also supply complete interfaces from a minimal set of methods. This magic checks names rather than signatures, accepts registered classes on trust, and carries a metaclass that may conflict with others, so it complements static checking rather than replacing it. Abstract methods are found, like any other attribute, by following the method resolution order of the class hierarchy, a mechanism that is developed in a future article of this series.