Sub topic 3
Declaring required methods with @abstractmethod
This chapter assumes you can write classes with inheritance, use decorators, and handle exceptions with try/except. It also assumes you know that ABC is the base class that gives a class abstract behavior. Here you will look at what @abstractmethod does to a function, how Python decides which methods are still missing, and where the mechanism does less than people expect.
What the decorator does
@abstractmethod is small. It sets one attribute on the function it wraps, __isabstractmethod__ = True, and returns the same function. It does not wrap the function or change how it runs.
The enforcement comes from ABCMeta, the metaclass of ABC. When a class is created, ABCMeta scans for functions flagged this way and stores their names in a frozenset called __abstractmethods__. When you later call the class, object.__new__ checks that set. If it is not empty, Python raises TypeError.
import json
from abc import ABC, abstractmethod
class Exporter(ABC):
@abstractmethod
def serialize(self, data: dict) -> str:
"""Convert data to a string."""
@abstractmethod
def extension(self) -> str:
"""Return the file extension, without the dot."""
print(Exporter.serialize.__isabstractmethod__)
print(sorted(Exporter.__abstractmethods__))
class JsonExporter(Exporter):
def serialize(self, data: dict) -> str:
return json.dumps(data)
print(sorted(JsonExporter.__abstractmethods__))
try:
JsonExporter()
except TypeError as exc:
print("TypeError:", exc)
class FullJsonExporter(JsonExporter):
def extension(self) -> str:
return "json"
exporter = FullJsonExporter()
print(exporter.serialize({"a": 1}), exporter.extension())The first lines print True and ['extension', 'serialize']. JsonExporter implements only serialize, so its set shrinks to ['extension'] and instantiation fails. The error message names the missing method. Its exact wording varies between Python versions, so do not match on it in tests. FullJsonExporter fills the last gap, its set becomes empty, and it can be created.
The set is the thing to inspect when you are unsure why a class is still abstract.
How Python computes the set
The set is not just "methods decorated in this class". ABCMeta builds it in two steps when a class is created:
- It adds every name in the new class body whose value has
__isabstractmethod__set to true. - For every name in each base class's
__abstractmethods__, it looks the name up on the new class withgetattr. If the result still has a true__isabstractmethod__, the name stays in the set.
Because step 2 uses getattr on the new class, the method resolution order (MRO) applies. A concrete method inherited from another base class also resolves an abstract name, even if the class body does not define it.
What counts as an implementation
Python checks one thing: whether the name, looked up on the class, still carries the abstract flag. That makes the check shallow.
| Situation | Result |
|---|---|
| Subclass defines a normal method with the same name | Name is removed from the set |
| Subclass redefines the method and decorates it with `@abstractmethod` again | Name stays abstract |
| Subclass sets the name to a non-function such as `None` | Name is removed from the set |
| Subclass defines the method with a different signature | Name is removed from the set |
| Method is added to the class after it is created | Set is not updated |
The next example shows the last three rows.
from abc import ABC, abstractmethod, update_abstractmethods
class Base(ABC):
@abstractmethod
def run(self) -> int:
...
class Disabled(Base):
run = None
class WrongSignature(Base):
def run(self, a, b, c):
return a + b + c
print(Disabled.__abstractmethods__)
print(WrongSignature.__abstractmethods__)
print(type(Disabled()).__name__, type(WrongSignature()).__name__)
class Late(ABC):
pass
Late.extra = abstractmethod(lambda self: None)
print(type(Late()).__name__)
update_abstractmethods(Late)
try:
Late()
except TypeError:
print("Late is abstract now")Both Disabled and WrongSignature can be instantiated, and both print frozenset(). abc does not compare signatures or return types. A type checker such as mypy can catch an incompatible override, but the runtime will not. Assigning run = None is a legitimate way to opt out of a method, but it is also an easy way to hide a missing one.
Late shows that the set is computed once. Adding an abstract method afterward has no effect until you call abc.update_abstractmethods, available since Python 3.10, to recompute it. Most code never needs this. It matters if you build classes dynamically or patch them in tests.
Abstract methods can have bodies
An abstract method does not have to be empty. Python does not care what the body contains. A subclass must still override the method, but it can call the base version with super().
from abc import ABC, abstractmethod
class Handler(ABC):
@abstractmethod
def handle(self, event: str) -> list[str]:
"""Subclasses must override this and may call it for the audit trail."""
return [f"logged {event}"]
class EmailHandler(Handler):
def handle(self, event: str) -> list[str]:
steps = super().handle(event)
steps.append(f"emailed {event}")
return steps
print(EmailHandler().handle("signup"))This prints ['logged signup', 'emailed signup']. It is useful when every implementation needs the same setup or logging, but you still want to force each subclass to make a conscious choice. If a base body does real work, document that subclasses are expected to call super(). Nothing enforces that.
A body of only a docstring or ... returns None. If a subclass calls super().handle() on such a method by mistake, it silently gets None.
Common errors
Forgetting the metaclass. @abstractmethod only sets a flag. Without ABC or metaclass=ABCMeta in the class hierarchy, nothing reads the flag.
from abc import abstractmethod
class Plain:
@abstractmethod
def run(self):
...
print(Plain().run())This prints None with no error. If your abstract class is not raising TypeError, check the base classes first.
Expecting an error at class definition. Defining class Broken(Shape): pass succeeds. The error appears only when you call Broken(). A missing method in a rarely used subclass can therefore stay hidden until that code path runs. Tests that instantiate each concrete class catch this early.
Putting @abstractmethod outermost. When you combine it with @property, @classmethod or @staticmethod, @abstractmethod must be the innermost decorator, directly above def. The following chapters cover the details. The ordering rule exists because abstractmethod sets its flag on whatever object it receives, and the outer decorators need to wrap the flagged function.
Assuming the check is a design guarantee. Python also lets you bypass instantiation checks in unusual ways, for example by calling object.__new__(cls) directly. In normal code, TypeError at instantiation is reliable, but it is a guard against mistakes and not a security boundary.
Choosing what to make abstract
Make a method abstract when two conditions hold. First, every subclass must provide its own behavior, because no sensible default exists. Second, the base class or its callers need to call that method. If a reasonable default exists, write a normal method that subclasses may override. If only some subclasses need a capability, a separate base class or mixin is often cleaner than a method that many subclasses implement as raise NotImplementedError.
Compare this with the older pattern of raising NotImplementedError in the base method. That pattern fails only when the method is called, possibly deep inside a program. @abstractmethod fails at object creation, which is much closer to the mistake. This is the main practical benefit.
Exercise
Given class A(ABC) with abstract methods f and g, and class B(A) that defines only f, what does B.__abstractmethods__ contain? What happens if class C(B) defines g as g = None, and you call C()?
Show answer
B.__abstractmethods__ is frozenset({'g'}), so B() raises TypeError. For C, getattr(C, 'g') returns None, which has no true __isabstractmethod__, so g is dropped from the set. C.__abstractmethods__ is frozenset() and C() succeeds, even though g does nothing useful.
Exercise
This code prints None and raises no error. Why, and what is the one-line fix?
from abc import abstractmethod
class Store:
@abstractmethod
def save(self, item): ...
print(Store().save(1))
Show answer
Store does not use ABC or ABCMeta, so nothing reads the __isabstractmethod__ flag and instantiation is never checked. Change the first line of the class to class Store(ABC): and import ABC from abc. Then Store() raises TypeError.