Sub topic 2
Creating an abstract base class with ABC
This chapter assumes you can define classes and use inheritance, and that you know decorators at a basic level. You should also be comfortable with try/except. Here you will create an abstract base class (ABC), see what ABC and ABCMeta each do, and learn which mistakes beginners usually make.
The simplest way: inherit from ABC
An abstract base class is a class that other classes inherit from but that is not meant to be used on its own. In Python you create one by inheriting from abc.ABC.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self) -> float:
"""Return the area of the shape."""
print(type(Shape))
print(Shape.__abstractmethods__)
try:
Shape()
except TypeError as exc:
print("TypeError:", exc)The first print shows <class 'abc.ABCMeta'>. The second shows frozenset({'area'}). The try block catches a TypeError, because Shape still has an abstract method.
Inheriting from ABC does not make the class abstract by itself. The class becomes abstract only when it has at least one method marked with @abstractmethod. The next chapter covers that decorator in detail.
What ABC and ABCMeta each do
ABC is a small helper class. It is defined as class ABC(metaclass=ABCMeta). A metaclass is the class of a class. Python uses it to build the class object when it runs a class statement.
ABCMeta is the metaclass that does the real work. Each time a class is created, ABCMeta looks through the class and its bases for methods marked abstract. It stores the names it finds in the class attribute __abstractmethods__. When you later call the class to make an instance, object.__new__ checks that set. If it is not empty, Python raises TypeError.
Because ABC only sets the metaclass, these two definitions are equivalent:
from abc import ABC, ABCMeta
class A(ABC):
pass
class B(metaclass=ABCMeta):
pass
print(type(A) is type(B))This prints True. Prefer ABC because it is shorter and easier to read. Use metaclass=ABCMeta only when you need to write the metaclass explicitly, for example when combining it with another metaclass.
How the check works
The following diagram shows when each step happens.
Two details follow from this flow:
- The check runs at instantiation, not when the class is defined. A broken subclass defines without any error, and the failure appears only when you call it.
- A subclass that overrides every abstract method gets an empty
__abstractmethods__, so it can be instantiated.
An ABC without abstract methods
An ABC with no abstract methods can be instantiated. Nothing in __abstractmethods__ means nothing to block.
from abc import ABC
class Base(ABC):
pass
print(Base())
print(Base.__abstractmethods__)This creates an object and prints frozenset(). If you want a class that nobody can instantiate, it needs at least one abstract method.
Common errors
- Forgetting to inherit from
ABC.@abstractmethodon a plain class has no effect, because the metaclass that reads it is missing. The class can be instantiated, and the method is just an ordinary method. - Expecting an error at class definition. The
TypeErrorappears only when you create an instance. - Metaclass conflicts. If another base class uses a different metaclass, combining it with
ABCraisesTypeError: metaclass conflict. The fix is a custom metaclass that inherits from both. This is rare in everyday code.
Exercise
Exercise
A class Report inherits from ABC but defines no abstract methods. Does Report() raise TypeError? What must you add so that it does, and when does the error appear?
Show answer
No, Report() succeeds, because __abstractmethods__ is empty. Add at least one method decorated with @abstractmethod. The TypeError then appears when you call Report() to create an instance, not when the class is defined.