Sub topic 1
Why abstract base classes exist
Prerequisites
This chapter assumes you can:
- define classes and use inheritance in Python
- tell instance methods, class methods and static methods apart
- read the
@propertydecorator and basic decorator syntax - handle exceptions with
try/except
The problem: interfaces that fail late
Suppose your program exports data, and each export format is a class. You want every exporter to have an export method. A common first attempt is a plain base class whose method raises NotImplementedError.
class Exporter:
def export(self, rows: list[dict]) -> str:
raise NotImplementedError("subclasses must implement export")
class CsvExporter(Exporter):
def export(self, rows: list[dict]) -> str:
return "\n".join(",".join(str(v) for v in row.values()) for row in rows)
class JsonExporter(Exporter):
def exprot(self, rows: list[dict]) -> str: # typo in the method name
return str(rows)
exporter = JsonExporter() # no error here
print("created", type(exporter).__name__)
try:
exporter.export([{"a": 1}])
except NotImplementedError as exc:
print("NotImplementedError:", exc)The typo in JsonExporter goes unnoticed when the class is defined and when the object is created. The error appears only when some code path finally calls export. In a large program, that call might sit in a rarely used branch and fail in production.
This pattern has three weaknesses:
- Nothing marks which methods a subclass is required to override.
- The base class itself can be instantiated, even though it does nothing useful.
- The failure happens far from the mistake.
What an abstract base class changes
An abstract base class (ABC) is a class that declares methods subclasses must implement and cannot be instantiated until they do. Python's abc module provides the tools. Here is the same design as an ABC.
from abc import ABC, abstractmethod
class Exporter(ABC):
@abstractmethod
def export(self, rows: list[dict]) -> str:
"""Return the rows serialized as text."""
class JsonExporter(Exporter):
def exprot(self, rows: list[dict]) -> str: # same typo
return str(rows)
try:
JsonExporter()
except TypeError as exc:
print("TypeError:", exc)Now the mistake surfaces on the line that creates the object. The TypeError message names the class and the missing method. The exact wording varies between Python versions. Trying Exporter() directly fails the same way.
What ABCs give you
- Early failure. An incomplete subclass cannot produce objects, so the error appears at creation time rather than at first use.
- A documented contract. Every
@abstractmethodis a visible list of what a subclass must provide. - Shared code. An ABC can also hold ordinary methods that build on the abstract ones. Later chapters cover this.
- Type checks that mean something. Code can ask
isinstance(obj, Exporter)and trust that the object supports the interface.
When to reach for one
Use an ABC when you control a family of classes that must share an interface, and you want mistakes caught early. Typical cases are plugin systems, backends for storage or messaging, and framework base classes that users extend.
Skip it when a single function or a duck-typed call is enough. Python does not require interfaces, and an ABC adds a base class every implementer must know about. A later chapter compares ABCs with typing.Protocol, which describes an interface without inheritance.
Where this fits
The next chapters build the pieces in order: ABC and its metaclass ABCMeta, the @abstractmethod decorator, abstract properties and class methods, then isinstance, virtual subclasses and the ABCs in collections.abc.
Exercise
A teammate writes a base class whose methods all raise NotImplementedError. A subclass forgets one method, and the bug reaches production. Name two ways converting the base class to an ABC with @abstractmethod would have changed this.
Show answer
First, creating an instance of the incomplete subclass raises TypeError immediately, so the bug appears at object creation, in tests or at startup, instead of when the missing method is first called. Second, the base class itself can no longer be instantiated, and the abstract methods act as a visible list of what every subclass must implement.