Sub topic 3
Declaring required methods with @abstractmethod
This chapter assumes you can write classes with inheritance, know how decorators work, and have seen ABC used as a base class. Here you will see what @abstractmethod records, how a subclass satisfies it, and where it silently does nothing.
What the decorator does
@abstractmethod marks a method as one that concrete subclasses must override. It does this by setting an attribute, __isabstractmethod__, to True on the function. It does not change how the function runs.
The metaclass ABCMeta (the metaclass behind ABC) reads that flag when the class is created. It collects the names of all abstract methods into a frozen set called __abstractmethods__. You can inspect it directly.
import json
from abc import ABC, abstractmethod
class Exporter(ABC):
@abstractmethod
def serialize(self, data: dict) -> str:
"""Turn data into text."""
@abstractmethod
def extension(self) -> str:
"""Return the file extension, such as 'json'."""
class JsonExporter(Exporter):
def serialize(self, data: dict) -> str:
return json.dumps(data)
print(Exporter.serialize.__isabstractmethod__)
print(sorted(Exporter.__abstractmethods__))
print(sorted(JsonExporter.__abstractmethods__))The output is:
True
['extension', 'serialize']
['extension']JsonExporter overrode serialize, so that name left the set. It did not override extension, so the name stays and JsonExporter is still abstract.
How the set is computed
When a subclass is created, ABCMeta starts from the abstract names declared in the class body. It then looks at every name that the parent classes listed as abstract and checks what the new class resolves that name to. If the resolved attribute still has __isabstractmethod__ set to true, the name stays in the set.
Any non-abstract attribute with the same name satisfies the requirement. The check is by name only. Python does not compare signatures, so a subclass can override serialize(self) with the wrong parameters and the class still instantiates.
Abstract methods can have a body
The decorated method may contain real code. Subclasses can reach it with super(), which is useful for shared setup or default behavior that each subclass must still extend explicitly.
from abc import ABC, abstractmethod
class Logger(ABC):
@abstractmethod
def write(self, message: str) -> None:
print(f"[base] {message}")
class ConsoleLogger(Logger):
def write(self, message: str) -> None:
super().write(message)
print(f"[console] {message}")
ConsoleLogger().write("started")This prints [base] started and then [console] started. The subclass must define write, but it chooses whether to call the base version.
Common errors
The decorator is easy to misuse in ways that raise no error at all.
- Forgetting the metaclass.
@abstractmethodonly has an effect when the class usesABCMeta. A plain class with the decorator can be instantiated freely. - Expecting an error at class definition. Python reports missing methods when you create an instance, not when you write the subclass. An incomplete subclass can exist and be passed around until someone calls it.
- Overriding with another abstract method. Re-decorating the name in a subclass keeps it abstract.
- Assigning after creation. Adding a method to a class later does not update
__abstractmethods__, unless you callabc.update_abstractmethods(cls)(Python 3.10+).
from abc import abstractmethod
class NotChecked:
@abstractmethod
def run(self) -> None:
...
NotChecked().run()
print("No error: NotChecked does not use ABCMeta")When you combine @abstractmethod with @property, @classmethod or @staticmethod, it must be the innermost decorator, directly above def. Later chapters cover those forms.
Summary
@abstractmethodsets__isabstractmethod__ = Trueon a function.ABCMetagathers those names into__abstractmethods__for each class.- A subclass satisfies a requirement by defining any non-abstract attribute with the same name.
- The check looks at names only, not signatures, and only works with
ABCorABCMeta.
Exercise
A class Base inherits from ABC and declares abstract methods load and save. Child(Base) defines load as a normal method and nothing else. What does sorted(Child.__abstractmethods__) return, and what would change if Base did not inherit from ABC?
Show answer
It returns ['save'], because load was overridden and save was not, so Child stays abstract. If Base did not inherit from ABC (and had no ABCMeta metaclass), the decorator would have no effect. __abstractmethods__ would not be computed, and Child() would instantiate without error.