Sub topic 8
Requiring overrides with abstract base classes
This chapter assumes you can define classes, override methods, and call the parent with super(). It also assumes you know what polymorphism means: calling one method name on objects of different subclasses. Here you will learn how to make Python enforce the rule that a subclass must provide certain methods.
The problem: overrides that nobody is forced to write
A base class often describes a contract. Every shape has an area, every payment processor can charge a card, and every exporter can write a file. The base class cannot supply a sensible area for "a shape in general", so each subclass must supply its own.
Without enforcement, you have two weak options. You can leave the method out and get an AttributeError later, or you can raise NotImplementedError in the base method and get an error only when someone calls it. Both fail late, possibly in production, far from the mistake.
An abstract base class (ABC) moves that failure to the moment you try to create an object. The abc module in the standard library provides the tools.
Declaring an abstract method
To make an ABC, inherit from abc.ABC and mark each required method with @abstractmethod.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
...
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
shapes = [Square(2), Square(3)]
print([s.area() for s in shapes]) # [4, 9]
try:
Shape()
except TypeError as exc:
print("Cannot instantiate:", exc)Three things happen here:
Shapecan be defined without any error, even thoughareahas no body.Squareoverridesarea, soSquare(2)works.Shape()raisesTypeError. The exact message wording differs between Python versions, but it names the class and the missing method.
The body ... is a placeholder that does nothing. A docstring also works as a body and documents what subclasses should do.
When and how Python checks
The check does not happen when you define a subclass. It happens when you instantiate. Defining a class that forgets an abstract method is legal. You only get the error when you call the class to create an object.
Python tracks the unresolved names in a class attribute named __abstractmethods__. When a class is created, Python collects every abstract name from its bases and removes the ones the class has overridden with a concrete attribute. If anything remains, object.__new__ refuses to build an instance.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
...
@abstractmethod
def perimeter(self):
...
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * self.radius ** 2
print(Shape.__abstractmethods__ == frozenset({"area", "perimeter"})) # True
print(Circle.__abstractmethods__) # frozenset({'perimeter'})
try:
Circle(1)
except TypeError as exc:
print("Cannot instantiate:", exc)Circle is a partial implementation. It stays abstract until a further subclass implements perimeter. This is useful for building a hierarchy in layers, where each layer fills in some of the contract.
The diagram below shows the decision made at instantiation time.
Concrete methods in an abstract class
An ABC can mix abstract and ordinary methods. The ordinary methods are inherited as usual and can call the abstract ones through self. This is sometimes called the template method pattern. The base class fixes the overall steps, and subclasses fill in the variable parts.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
...
def describe(self):
return f"{type(self).__name__} with area {self.area():.2f}"
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
print(Rectangle(2, 3).describe()) # Rectangle with area 6.00describe() is written once and works for every subclass. This is polymorphism with a guarantee: because Shape cannot be instantiated without area, describe() can rely on self.area() existing.
Abstract methods can have a body
@abstractmethod only forces subclasses to override the name. The base version can still contain real code, and a subclass can reach it with super().
from abc import ABC, abstractmethod
class Greeter(ABC):
@abstractmethod
def greet(self):
return "Hello"
class Polite(Greeter):
def greet(self):
return super().greet() + ", pleased to meet you"
print(Polite().greet()) # Hello, pleased to meet youUse this when there is a useful default that each subclass should consciously extend. It makes the override mandatory while still sharing code.
Abstract properties
A property can also be required. Stack @property on the outside and @abstractmethod directly above the function.
from abc import ABC, abstractmethod
class Account(ABC):
@property
@abstractmethod
def balance(self):
...
class Savings(Account):
def __init__(self, amount):
self._amount = amount
@property
def balance(self):
return self._amount
print(Savings(50).balance) # 50The order matters. @abstractmethod must be the innermost decorator, the one closest to def. If you reverse the order, the abstract flag is lost and the check silently does nothing.
The same pattern works with @classmethod and @staticmethod: put @abstractmethod innermost.
What the check does not cover
The check is narrow. Know its limits so you do not overtrust it.
- Names only. Python checks that a name was overridden. It does not compare signatures, so
def area(self, extra, args)satisfies the requirement even though callers will break. - Any attribute counts. A class attribute such as
balance = 10in a subclass also clears the abstract name, because it replaces the abstract attribute. - Return values are not checked. An override that returns
Noneis accepted. - Instantiation only. Class methods and static methods that are abstract can still be called on the ABC itself, since no instance is needed.
Signature and type compatibility are the job of tests and static type checkers, not of abc.
Common errors
The most common mistake is writing @abstractmethod in a class that does not inherit from ABC. The decorator only sets a flag. The machinery that reads the flag lives in the ABCMeta metaclass, which ABC supplies.
from abc import abstractmethod
class NotAbstract:
@abstractmethod
def run(self):
...
obj = NotAbstract() # no error: nothing enforces the flag
print(type(obj).__name__) # NotAbstractOther frequent problems:
- Misspelled override. If the base declares
areaand the subclass definesaera, instantiation fails with aTypeError. This is the check working as intended, but the error can look confusing at first. Read the method name in the message. - Forgetting
super().__init__(). ABCs do not change constructor rules. If an abstract base defines__init__that sets up state, subclasses must still chain to it. - Calling
Shape()in tests. Tests that try to build the base class directly will fail. Instantiate a small concrete subclass instead. - Decorator order on properties. As covered above,
@propertygoes outside and@abstractmethodinside.
ABC versus `NotImplementedError`
Both approaches say "subclasses must provide this", but they fail at different times.
| Approach | Error raised | When it fails | Instantiating the base |
|---|---|---|---|
| `ABC` with `@abstractmethod` | `TypeError` | When the object is created | Blocked |
| `raise NotImplementedError` in the base method | `NotImplementedError` | When the method is called | Allowed |
Prefer an ABC when the requirement is part of the class's identity and you want mistakes caught early. Use NotImplementedError for optional hooks, or when the base class must remain instantiable. Note that NotImplementedError is also the right choice for binary operators such as __add__, where it is returned as NotImplemented to signal "I don't handle this type".
Registering classes you cannot change
An ABC also acts as a type that isinstance() and issubclass() understand. Its register() method declares an existing class to be a virtual subclass, without inheritance.
from abc import ABC, abstractmethod
class Drawable(ABC):
@abstractmethod
def draw(self):
...
class Sprite:
def draw(self):
return "sprite drawn"
Drawable.register(Sprite)
print(isinstance(Sprite(), Drawable)) # True
print(issubclass(Sprite, Drawable)) # True
print(Drawable in Sprite.__mro__) # FalseA registered class passes type checks, but Python does not verify that it implements the abstract methods. It also does not appear in the method resolution order, so it inherits nothing from the ABC. Registration is a promise you make, not a check Python performs. Many standard-library ABCs in collections.abc, such as Sized and Iterable, use a related hook to recognize classes automatically.
Choosing when to use an ABC
Use an ABC when:
- several subclasses share a real contract and a shared concrete helper such as
describe(); - you want the failure at construction, not deep inside a later call;
- the base class would be meaningless as a standalone object.
Skip it when a single function would do, when the "contract" is one method that a plain callable could supply, or when you only need structural typing for a type checker. In that case typing.Protocol may fit better, but that is a separate tool.
Exercise
Given the code below, which line raises TypeError, and why? How would you fix it so that "Dog" prints? from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def speak(self): ... class Dog(Animal): def bark(self): return "Woof" print(Dog()._class.name_)
Show answer
The line Dog() raises TypeError. Dog inherits the abstract method speak and only defines bark, so Dog._abstractmethods_ still contains "speak" and Python refuses to instantiate it. Fix it by overriding speak in Dog, for example def speak(self): return "Woof". After that, Dog() succeeds and the program prints Dog.
Exercise
A teammate writes a class with @abstractmethod on run, but the class is declared as class Task: with no base. Task() works without error. Why, and what is the minimal change that makes Python enforce the rule?
Show answer
The @abstractmethod decorator only marks the function. The enforcement is done by the ABCMeta metaclass, which a plain class does not use. Change the declaration to class Task(ABC): (importing ABC from abc), or use metaclass=ABCMeta. Then Task() raises TypeError, and only subclasses that override run can be instantiated.