Sub topic 13
Common pitfalls and design guidelines
This chapter assumes you can define classes and subclasses, use @abstractmethod with ABC, and read a try/except block. It covers where abstract base classes (ABCs) fail to protect you, and how to design with them.
Pitfall 1: no `ABC` base, no enforcement
@abstractmethod only marks a method. The check happens in ABCMeta, the metaclass that ABC supplies. Without it, the decorator does nothing.
from abc import ABC, abstractmethod
class NoMeta:
@abstractmethod
def run(self) -> None: ...
class Task(ABC):
@abstractmethod
def run(self) -> None: ...
print(NoMeta()) # works: nothing is enforced
try:
Task()
except TypeError:
print("Task cannot be instantiated")Pitfall 2: expecting an error at class definition
Python checks abstract methods when you create an object, not when you define a subclass. An incomplete subclass can sit in your code for a long time before it fails.
from abc import ABC, abstractmethod
class Task(ABC):
@abstractmethod
def run(self) -> None: ...
class Partial(Task):
pass # no error here
print(Partial.__abstractmethods__) # frozenset({'run'})
try:
Partial()
except TypeError as exc:
print("TypeError:", exc)The __abstractmethods__ attribute lists what is still missing. Instantiate every concrete class in a test so the error appears in your test run and not in production.
Pitfall 3: registered classes are not checked
register makes isinstance return True. It does not verify that the class implements anything.
from abc import ABC, abstractmethod
class Task(ABC):
@abstractmethod
def run(self) -> None: ...
class Fake:
pass
Task.register(Fake)
obj = Fake()
print(isinstance(obj, Task)) # True
try:
obj.run()
except AttributeError as exc:
print("AttributeError:", exc)Code that trusts isinstance(obj, Task) will then crash at the call site. Register only classes you have checked yourself. The same applies to __subclasshook__, which usually tests method names and nothing else.
Pitfall 4: signatures are not compared
Python checks that an override exists, not that it matches. A subclass can change the parameters and still be instantiable.
from abc import ABC, abstractmethod
class Task(ABC):
@abstractmethod
def run(self) -> None: ...
class Wrong(Task):
def run(self, required_extra: int) -> None:
print(required_extra)
Wrong() # no error; Wrong().run() would raise TypeErrorA type checker such as mypy catches this. The runtime does not.
Smaller traps
- Decorator order. With
@property,@classmethodor@staticmethod, put@abstractmethodinnermost, directly abovedef. - Late changes. Adding an abstract method to a base class breaks every existing subclass at its next instantiation. Treat abstract methods as part of your public API.
- Abstract does not mean empty. An abstract method may have a body. Subclasses can reach it with
super().
Design guidelines
- Keep interfaces small. Two or three abstract methods are easier to implement and to test than ten.
- Put shared logic in concrete methods. Let a template method call the abstract steps, as
describedid witharea. - Prefer
collections.abcover inventing your own. If your class is a mapping or a sequence, subclassMappingorSequenceand get the mixin methods. - Use ABCs when you own the hierarchy. You want an explicit "is a" relationship, shared code, and an early error.
- Use
typing.Protocolwhen you do not own the classes. Structural matching works without inheritance or registration. - Avoid long
isinstancechains. If you branch on many ABC types, move the behavior into methods on the classes.
Exercise
A class Report is registered with Exporter.register(Report), and Exporter has an abstract method export. Report does not define export. What do isinstance(Report(), Exporter) and Report().export() do?
Show answer
isinstance returns True, because registration declares Report a virtual subclass without checking its methods. Report().export() raises AttributeError, because the method does not exist. Python never runs the abstract-method check for registered classes.
Exercise
You add a new @abstractmethod called validate to a base class that already has three subclasses in production. What happens, and how can you avoid it?
Show answer
Each existing subclass raises TypeError the next time it is instantiated, because validate is now abstract and unimplemented. To avoid this, give validate a concrete default in the base class, or update every subclass in the same change. Instantiating each subclass in a test catches the problem early.