Sub topic 2
Creating an abstract base class with ABC
This chapter covers the machinery behind abstract base classes: the ABC helper class, the ABCMeta metaclass, and what each one adds to a class you write. It assumes you can define classes and use inheritance, know what a decorator is, and can read a try/except block. You should also know that a class is itself an object created by something else, though you don't need to have written a metaclass.
Two ways to ask for the same thing
An abstract base class (ABC) in Python is a class whose metaclass is abc.ABCMeta. The metaclass is what does the work. Everything else in the abc module, including @abstractmethod, depends on it.
You can request ABCMeta in two ways. The first, and the usual one, is to inherit from abc.ABC. The second is to name the metaclass explicitly.
from abc import ABC, ABCMeta, abstractmethod
class A(ABC):
@abstractmethod
def run(self): ...
class B(metaclass=ABCMeta):
@abstractmethod
def run(self): ...
print(type(A))
print(type(B))
print(ABC.__mro__)
print(A.__abstractmethods__)Running it prints:
<class 'abc.ABCMeta'>
<class 'abc.ABCMeta'>
(<class 'abc.ABC'>, <class 'object'>)
<frozenset({'run'})>The last line is frozenset({'run'}), without the angle brackets. type(A) and type(B) are the same. ABC is an ordinary class that exists only so you can write class A(ABC) instead of class A(metaclass=ABCMeta). Its definition in the standard library is essentially this:
class ABC(metaclass=ABCMeta):
__slots__ = ()So ABC does nothing beyond carrying the metaclass to its subclasses. The empty __slots__ means inheriting from it does not add a per-instance __dict__. Your subclass still gets one unless you declare __slots__ yourself.
What the metaclass does
A metaclass is the class of a class. When Python runs a class statement, it collects the body into a namespace dictionary and calls the metaclass with the class name, the bases, and that namespace. For a normal class the metaclass is type. ABCMeta is a subclass of type, so it can do extra work at that moment.
ABCMeta adds three things to the classes it creates:
- A set of abstract names. When a class is created,
ABCMetascans the namespace and the bases and stores the result in__abstractmethods__. A name is in the set if it is marked abstract in the class body, or if it was abstract in a base class and has not been overridden with a non-abstract definition. - An instantiation guard. The built-in
object.__new__checks whether the class has a non-empty__abstractmethods__. If it does, creating an instance raisesTypeError. The next chapters look at this check in detail. - Customized
isinstanceandissubclass.ABCMetadefines__instancecheck__and__subclasscheck__, and aregistermethod. These let a class claim membership without inheriting, which later chapters cover.
The first point matters for the rest of this chapter. The set is computed once, when the class statement runs. It is not recomputed each time you create an instance.
Inherited abstractness
An abstract method that you do not override stays abstract in the subclass. The subclass is still an abstract class, and defining it is not an error.
from abc import ABC, abstractmethod
class Reader(ABC):
@abstractmethod
def read(self): ...
@abstractmethod
def close(self): ...
class PartialReader(Reader):
def read(self):
return "data"
print(sorted(Reader.__abstractmethods__))
print(sorted(PartialReader.__abstractmethods__))Output:
['close', 'read']
['close']PartialReader implements read but not close, so close remains in its set. A further subclass that defines close would end up with an empty set and become instantiable. You can read __abstractmethods__ to see which names a class still owes, which is useful when debugging a TypeError about a class with many abstract methods.
An ABC is not required to have abstract methods
Inheriting from ABC does not make a class uninstantiable. Only a non-empty __abstractmethods__ does that.
from abc import ABC
class Base(ABC):
pass
print(type(Base()))
print(Base.__abstractmethods__)Output:
<class '__main__.Base'>
frozenset()This is a common surprise. A class with no abstract members is concrete as far as Python is concerned, even though you may have meant it to be a pure base. If you want a base that cannot be created directly but has no natural abstract method, you need to mark something abstract, or raise an error in __init__ yourself. The usual choice is to find the method subclasses must supply and mark that one.
The decorator needs the metaclass
@abstractmethod only sets a flag, __isabstractmethod__ = True, on the function. The flag has no effect unless ABCMeta reads it when the class is built. Without the metaclass, the decorator is silently ignored.
from abc import abstractmethod
class Plain:
@abstractmethod
def run(self):
return "ran"
print(Plain().run())
print(Plain.run.__isabstractmethod__)Output:
ran
TrueThe flag is set, but Plain was built by type, so nothing checks it. This is a frequent bug: someone adds @abstractmethod to a class that does not inherit from ABC and believes the interface is now enforced. The next chapter covers the decorator itself.
Checking happens at instantiation, not at definition
Because ABCMeta only records the set when the class is created, a mistake in a subclass appears when you first try to create an object, not when you write the class statement.
from abc import ABC, abstractmethod
class Task(ABC):
@abstractmethod
def execute(self): ...
class Forgetful(Task):
pass # no error here
print("class defined")
try:
Forgetful()
except TypeError as exc:
print("TypeError raised")Output:
class defined
TypeError raisedIf a class is defined at import time but only instantiated deep in a rarely run code path, the error can stay hidden for a long time. Tests that instantiate every concrete subclass at least once catch this early. A type checker such as mypy also reports it, because it knows the class is abstract.
Metaclass conflicts
A class can have only one metaclass, and Python requires the metaclass of a derived class to be a subclass of the metaclasses of all its bases. If you inherit from ABC and from a class that uses a different metaclass, neither is a subclass of the other, and class creation fails.
from abc import ABC, ABCMeta
class Meta(type):
pass
class Base(metaclass=Meta):
pass
try:
class Mixed(Base, ABC):
pass
except TypeError as exc:
print(type(exc).__name__)
class CombinedMeta(Meta, ABCMeta):
pass
class Fixed(Base, metaclass=CombinedMeta):
pass
print(type(Fixed).__name__)Output:
TypeError
CombinedMetaThe fix is to write a metaclass that inherits from both and pass it with metaclass=. This is the situation where metaclass=ABCMeta reads more naturally than ABC, because you are already naming a metaclass. Frameworks that ship their own metaclasses, such as some ORMs and enum-like libraries, usually document how to combine them with ABCMeta. Check there before writing your own.
Comparing the two spellings
| Aspect | `class X(ABC)` | `class X(metaclass=ABCMeta)` |
|---|---|---|
| Resulting metaclass | `ABCMeta` | `ABCMeta` |
| Adds a base class | Yes, `ABC` appears in `__mro__` | No |
| Typical use | New code, default choice | Combining with another metaclass, or code that must run on very old Python versions |
| Works with multiple inheritance | Yes, if other bases do not use a conflicting metaclass | Yes, and you can pass a combined metaclass |
Because ABC appears in the MRO, issubclass(X, ABC) is True for the first spelling and False for the second. Code that tests for ABC directly should be rare. Test against your own base class instead.
Changing a class after creation
The abstract set is fixed when the class is built. If you assign a method onto the class afterwards, __abstractmethods__ is not updated. Python 3.10 added abc.update_abstractmethods to recompute it. Class decorators that add or remove methods call it for you; for most hand-written code you will not need it.
from abc import ABC, abstractmethod, update_abstractmethods
class Job(ABC):
@abstractmethod
def go(self): ...
Job.go = lambda self: "late"
print(sorted(Job.__abstractmethods__))
update_abstractmethods(Job)
print(sorted(Job.__abstractmethods__))
print(Job().go())Output:
['go']
[]
lateBefore the call, Job still believed go was abstract, even though the replacement is a plain function. The function must be one that is not marked abstract, or recomputation keeps the name in the set.
Summary of working rules
- Inherit from
ABCto getABCMeta. The metaclass, not the base class, provides the behavior. __abstractmethods__is computed when the class is created and lists the names still unimplemented.- A class is uninstantiable only while that set is non-empty. Inheriting from
ABCalone is not enough. @abstractmethodon a class withoutABCMetahas no effect.- Errors appear at instantiation, so exercise every concrete subclass in tests.
- Mixing in a base with a different metaclass needs a combined metaclass.
Exercise
A teammate writes class Storage: @abstractmethod def save(self): ... (with from abc import abstractmethod, but no ABC base) and then calls Storage(). What happens, and what is the smallest change that makes Storage() raise TypeError?
Show answer
Storage() succeeds, because the class was built by type and nothing reads the __isabstractmethod__ flag. The smallest change is to make the class inherit from ABC (or use metaclass=ABCMeta). Then __abstractmethods__ contains save, and Storage() raises TypeError.
Exercise
Given class A(ABC) with abstract methods x and y, and class B(A) that defines only x, what is B.__abstractmethods__, and does the class B statement raise an error?
Show answer
B.__abstractmethods__ is frozenset({'y'}). The class B statement does not raise an error. TypeError is raised only if you try to instantiate B while y is still abstract.
Exercise
You have class Base(metaclass=Meta) where Meta is a custom subclass of type. class Child(Base, ABC) raises a metaclass conflict. Write the class statements that fix it.
Show answer
class CombinedMeta(Meta, ABCMeta): pass followed by class Child(Base, metaclass=CombinedMeta): .... The combined metaclass is a subclass of both Meta and ABCMeta, which satisfies Python's requirement for derived classes.