Sub topic 1
Why Abstract Base Classes Exist
Python does not require you to declare interfaces. If an object has a .read() method, you can call .read() on it. That flexibility is useful, but it has a cost. When many classes are supposed to share one set of methods, nothing in the language says which methods are required, and nothing complains when one is missing. Abstract base classes (ABCs) exist to fix this. This chapter explains the problem they solve, previews how they solve it, and helps you decide when to use one.
Prerequisites
This chapter assumes you can already do the following:
- Define classes and use inheritance, including calling overridden methods.
- Tell instance methods, class methods and static methods apart.
- Read and write the
@propertydecorator. - Apply decorators to functions and methods.
- Handle exceptions with
tryandexcept.
You do not need to know the abc module yet. The later chapters cover its pieces one by one.
The problem: an interface that exists only in your head
Suppose you write a small reporting tool. Several classes export rows of data, and the job runner calls export on whichever one it is given. The usual first attempt is a plain base class that documents the contract by raising NotImplementedError.
class Exporter:
def export(self, rows):
raise NotImplementedError("subclasses must implement export")
class CsvExporter(Exporter):
def export(self, rows):
return "\n".join(",".join(map(str, row)) for row in rows)
class JsonExporter(Exporter):
def exprot(self, rows): # typo: the method name is wrong
return "[]"
def run(exporter, rows):
print("starting job")
return exporter.export(rows)
print(run(CsvExporter(), [(1, 2), (3, 4)]))
try:
run(JsonExporter(), [(1, 2)])
except NotImplementedError as exc:
print("NotImplementedError:", exc)The code runs, and JsonExporter is defined and even instantiated without any complaint. The mistake only appears when export is called, and in a real program that could be far from where the class was written. By then the job may have already started, opened files or sent requests.
This pattern has three weaknesses:
- Late failure. The error appears at call time, not when the object is created. A rarely used code path can hide the bug for months.
- Weak documentation. A reader has to open the base class and look for methods that raise
NotImplementedErrorto learn what a subclass must provide. Tools cannot see this reliably either. - Wrong exception.
NotImplementedErrormeans "this operation is not available", which is also what you raise for legitimate reasons. It does not say "this class is incomplete".
What an abstract base class changes
An ABC moves the check from the call to the creation of the object. You declare which methods are required, and Python refuses to build an instance of any class that has not supplied all of them.
from abc import ABC, abstractmethod
class Exporter(ABC):
@abstractmethod
def export(self, rows):
"""Return the rows as a string."""
class CsvExporter(Exporter):
def export(self, rows):
return "\n".join(",".join(map(str, row)) for row in rows)
class JsonExporter(Exporter):
def exprot(self, rows): # same typo as before
return "[]"
print("classes defined")
print(CsvExporter().export([(1, 2)]))
try:
JsonExporter()
except TypeError as exc:
print("TypeError:", exc)The output shows classes defined and 1,2. Then Python raises TypeError with a message that names JsonExporter and the missing method export. The exact wording differs between Python versions. The typo is now reported at the line that creates the object, before any job logic runs.
Two details are worth noting now, because later chapters build on them:
- Defining the incomplete class is allowed. The error comes when you instantiate it, not when you write the
classstatement. - The method name is the contract.
exprotdoes not satisfyexport, so the subclass is still incomplete.
The three jobs of an abstract base class
An ABC is more than an error checker. In practice it does three jobs, and you can use any combination.
- It states a contract. The abstract methods are a list of what every implementation must provide. The list is in code, so tools and readers can find it.
- It shares behavior. An ABC can also contain ordinary methods that rely on the abstract ones. Subclasses fill in a few required pieces and inherit the rest. This is how
collections.abc.Mappingworks: you write__getitem__,__iter__and__len__, and you getget,items,keys,valuesandinfor free. - It defines a category for type tests.
isinstance(obj, SomeABC)asks "does this object belong to this family?" without caring about its exact class.
The third job is the one that surprises people. The standard library uses it everywhere:
from collections.abc import Iterable, Sized
print(isinstance([1, 2, 3], Iterable))
print(isinstance(5, Iterable))
print(isinstance("text", Sized))This prints True, False and True. Checking against a concrete class such as list would reject tuples, sets and generators that work just as well. Checking against Iterable accepts everything that can be looped over. A later chapter covers how isinstance and issubclass behave with ABCs, including classes that were never subclassed from them.
Why not just use duck typing?
Duck typing means you call the method and handle failure if it is missing. It is the default Python style, and it is often the right one. Use it when only one function consumes the object, the requirement is a single method, and failing at the call site is acceptable.
The case for an ABC grows with the number of implementations and the cost of a late failure. The table compares the approaches.
| Approach | When the error appears | Contract visible in code | Shared behavior | Needs inheritance |
|---|---|---|---|---|
| Duck typing only | At the call, as `AttributeError` | No, only in docs | No | No |
| Base class with `NotImplementedError` | At the call | Weakly | Yes | Yes |
| ABC with `@abstractmethod` | At instantiation, as `TypeError` | Yes | Yes | Yes, or registration |
| `typing.Protocol` | Before running, in a type checker | Yes | No | No |
The last row is covered in a later chapter. Protocols and ABCs solve overlapping problems, and the choice between them depends on whether you control the implementing classes and whether you want shared code.
When an ABC is a good fit
Reach for an ABC when several of these are true:
- You have, or expect, three or more implementations of the same idea, such as storage backends, exporters or payment providers.
- Other people write the subclasses, for example plugin authors, so the contract needs to be enforced and documented.
- Subclasses share logic that depends on a few required methods, which is the template-method pattern.
- You want a failure early, at construction, because a half-built object is dangerous.
- You want callers to test for a capability with
isinstanceinstead of a list of concrete types.
Skip the ABC when you have one implementation, when a plain function or a callable would do, or when the "interface" is a single method that you could pass in as an argument.
Common misunderstandings
These mistakes come up repeatedly, and each one is covered in detail later.
- Expecting an error when the class is defined. Python checks at instantiation. A class with missing methods can be defined, imported, subclassed again and used as a base without any error, as long as nobody creates an instance of it.
- Expecting
@abstractmethodto work on a plain class. The check is performed by theABCMetametaclass. A class that inherits fromobjectonly, with@abstractmethodon a method, is not checked at all. Inheriting fromABCsupplies that metaclass. - Thinking abstract methods cannot have a body. They can. A subclass can even call
super().export(rows)to reuse the body. The decorator only marks the method as one that must be overridden. - Assuming signatures are verified. A subclass whose
exporttakes different parameters still counts as implementing it. Python only checks that the name is overridden. - Using an ABC as a rule that applies to everything. Classes that are registered as virtual subclasses are not checked at all. A later chapter explains why.
Summary of the working model
An abstract base class is an ordinary class whose metaclass, ABCMeta, keeps track of which methods are still abstract. When you create an instance, Python looks at the abstract names that remain and raises TypeError if any are left. The same metaclass lets isinstance and issubclass answer questions about a family of classes, not only about the inheritance chain. The next chapters build on this: first how ABC and ABCMeta set it up, then how @abstractmethod marks the required methods.
Exercise
A teammate writes a base class Storage whose save method raises NotImplementedError. A subclass S3Storage misspells the method as sav. The bug is only found in production when a user triggers a save. Rewrite Storage as an ABC so the mistake surfaces earlier. At which exact moment will Python now report it, and which exception will it raise?
Show answer
Write class Storage(ABC): with @abstractmethod above def save(self, data): (importing ABC and abstractmethod from abc). Python will now raise TypeError when the code first tries to create an instance of S3Storage, for example S3Storage(), because save is still abstract in that class. It will not raise an error when the S3Storage class is defined, and it will not wait until save is called.
Exercise
Name the three jobs an ABC can do, and say which of them collections.abc.Mapping demonstrates when it gives you .get() and .items() after you write only __getitem__, __iter__ and __len__.
Show answer
An ABC can state a contract (the required methods), share behavior (concrete methods built on the required ones), and define a category for isinstance and issubclass checks. Providing .get() and .items() from the three required methods demonstrates shared behavior.