Sub topic 13
Common pitfalls and design guidelines
This chapter assumes you can define an ABC with @abstractmethod, you know how register and __subclasshook__ work, and you have seen typing.Protocol. It collects the mistakes that catch people in practice and ends with rules for deciding when an abstract base class (ABC) is the right tool.
When the check happens
Python checks abstract methods when you create an object. It does not check when you define a class. The check runs inside object.__new__, so it happens before __init__ starts.
from abc import ABC, abstractmethod
class Exporter(ABC):
@abstractmethod
def export(self, data: dict) -> str:
...
class HalfDone(Exporter):
pass
print("class defined without error")
print(HalfDone.__abstractmethods__)
try:
HalfDone()
except TypeError as exc:
print("TypeError raised at instantiation")
class NotAnABC:
@abstractmethod
def export(self, data: dict) -> str:
...
print(type(NotAnABC()).__name__)The output is:
class defined without error
frozenset({'export'})
TypeError raised at instantiation
NotAnABCThis shows three things:
HalfDoneis defined without complaint. A mistake in a rarely used subclass can stay hidden until the line that creates the object runs.__abstractmethods__is a frozenset of the names that are still unimplemented. It is useful when debugging.NotAnABCuses@abstractmethodbut does not inherit fromABC. Its metaclass is plaintype, so nothing is enforced.
The decorator only sets a flag. The metaclass ABCMeta reads that flag and does the enforcing.
If you want early failure, instantiate every concrete class in a test. A single test that creates one object per implementation catches a missing method before production does.
Pitfalls
Any attribute with the right name counts as an implementation
ABCMeta looks at each abstract name and checks whether the value on the new class is still marked abstract. It does not check that the value is callable or has the right signature.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self) -> float:
...
class Sloppy(Shape):
area = None
shape = Sloppy()
print(shape.area)
try:
shape.area()
except TypeError as exc:
print("TypeError:", exc)The output is None, then TypeError: 'NoneType' object is not callable. The instantiation succeeded because None is not abstract. ABCs check names, not signatures. A type checker such as mypy catches signature mismatches. Python at runtime does not.
Registered classes are not checked and get no mixins
register is a promise from you, and Python does not verify it. The registered class does not inherit the ABC's concrete methods either.
from abc import ABC, abstractmethod
class Reader(ABC):
@abstractmethod
def read(self) -> str:
...
def read_upper(self) -> str:
return self.read().upper()
class Plain:
pass
Reader.register(Plain)
plain = Plain()
print(isinstance(plain, Reader))
try:
plain.read_upper()
except AttributeError as exc:
print("AttributeError:", exc)isinstance returns True, but read_upper does not exist on Plain. Code that trusts isinstance(x, Reader) and then calls a mixin method will fail. Use register only for classes that really implement the whole interface and that you cannot edit. If you can change the class, inherit from the ABC instead.
The decorator order matters
When you combine @abstractmethod with @property, @classmethod or @staticmethod, @abstractmethod must be the innermost decorator, directly above def. The other decorator goes above it.
from abc import ABC, abstractmethod
class Account(ABC):
@property
@abstractmethod
def balance(self) -> int:
...With the order reversed, the abstract marker may be lost or an error may be raised, depending on the Python version. Copy the working order and do not rely on the failure being obvious.
Abstract methods added later are not noticed
ABCMeta computes __abstractmethods__ once, when the class is created. If you attach an abstract method to a finished class, for example from a class decorator or by assigning an attribute, the set is not updated. Python 3.10 added abc.update_abstractmethods(cls) for this case. Most code never needs it. Prefer declaring abstract methods in the class body.
Metaclass conflicts
ABC brings in the metaclass ABCMeta. If you inherit from an ABC and from a class that has a different custom metaclass, Python raises TypeError: metaclass conflict. The fix is a metaclass that inherits from both, or, more often, a design that avoids combining them. This is common with some ORM and enum base classes.
Abstract methods can still have a body
An abstract method may contain code, and subclasses can call it with super(). This is useful for shared setup. It also means a body of pass or ... is only a convention. Python does not require the body to be empty. A docstring is a good placeholder because it documents the contract.
Summary of failure modes
| Symptom | Likely cause | Fix |
|---|---|---|
| No error when creating an object that lacks a method | The class does not inherit from `ABC` or use `ABCMeta` | Inherit from `ABC` |
| Error appears only when a rare class is used | Enforcement happens at instantiation, not definition | Add a test that instantiates every implementation |
| `isinstance` is `True` but a method is missing | The class was registered or matched by `__subclasshook__` | Inherit instead, or check the methods you need |
| Subclass instantiates but crashes when called | A non-callable attribute replaced the abstract method | Review the class body, and run a type checker |
| Abstract property is not enforced | Wrong decorator order | Put `@abstractmethod` innermost |
| `metaclass conflict` error | Two bases with different metaclasses | Combine the metaclasses or change the design |
Design guidelines
Keep the abstract surface small
An ABC with ten abstract methods is hard to implement and hard to change. Each abstract method is a promise every subclass must keep. Split large interfaces into small ones, such as a reader and a writer, and let a class inherit from both when it needs both. Where you can, make the abstract methods the minimum set and build the rest from them as concrete methods. collections.abc.Mapping does this: three abstract methods give you get, items, keys, values and __contains__.
Put shared behavior in concrete methods
A good ABC separates what varies (the abstract methods) from what stays the same (the concrete methods). This is the template method pattern. The example below also shows a contract test that every implementation can pass.
from abc import ABC, abstractmethod
from typing import Optional
class Storage(ABC):
@abstractmethod
def get(self, key: str) -> Optional[str]:
"""Return the stored value, or None if the key is missing."""
@abstractmethod
def put(self, key: str, value: str) -> None:
"""Store a value under a key."""
def get_or(self, key: str, default: str) -> str:
value = self.get(key)
return default if value is None else value
class MemoryStorage(Storage):
def __init__(self) -> None:
self._items: dict[str, str] = {}
def get(self, key: str) -> Optional[str]:
return self._items.get(key)
def put(self, key: str, value: str) -> None:
self._items[key] = value
def check_storage_contract(make_storage) -> None:
store = make_storage()
assert isinstance(store, Storage)
assert store.get("a") is None
store.put("a", "1")
assert store.get("a") == "1"
assert store.get_or("b", "x") == "x"
print(type(store).__name__, "passes the contract")
check_storage_contract(MemoryStorage)The check creates an instance, so it also catches a missing abstract method. Because it takes a factory, you can run the same function against every new implementation. This covers what the ABC cannot enforce: return values and behavior.
Choose the tool by the situation
Use the questions below to decide between an ABC and a protocol.
Some further rules:
- Do not create an ABC when there is only one implementation and no plan for a second. A plain class is simpler. Add the ABC when the second implementation appears.
- Prefer shallow hierarchies. An ABC, then concrete classes, is usually enough. Deep chains of abstract classes make it hard to see which methods are still missing.
- Prefer composition when the relationship is "has a", not "is a". Pass a
Storageinto a class, and do not inherit from it. - Use
isinstancechecks against an ABC at the edges of your code, such as when validating input. Inside your code, trust the interface and call the methods. - Document the contract in docstrings: what each method returns, which exceptions it may raise, and any ordering rules. The decorator cannot express these.
- Use
Protocolfor typing when you only need static checking and the implementers are outside your control. Remember thatisinstancewith a runtime-checkable protocol checks only that the method names exist. It does not check signatures.
Exercises
Exercise
A teammate writes class Handler: with an @abstractmethod named handle, but forgets to inherit from ABC. Handler() runs without error. Why, and what is the smallest fix?
Show answer
Only ABCMeta enforces abstract methods, and the class uses the plain type metaclass, so @abstractmethod merely sets an unused flag. Change the definition to class Handler(ABC): (or metaclass=ABCMeta). Then Handler() raises TypeError.
Exercise
You register a class Legacy with an ABC called Sink that has an abstract method write and a concrete method write_all. A caller does if isinstance(obj, Sink): obj.write_all(items). What can go wrong with a Legacy object, and how do you avoid it?
Show answer
register does not copy the ABC's concrete methods onto Legacy, and Python does not check that Legacy implements write. obj.write_all raises AttributeError unless Legacy defines it. Avoid this by making Legacy inherit from Sink if you can edit it, by wrapping it in a small adapter class that inherits from Sink, or by having callers use only the methods that every registered class is known to provide.