Abstract base classes
An abstract base class (ABC) is a class that names methods subclasses must implement and that you cannot instantiate until they do. abc.ABC and @abstractmethod are the standard-library tools.
Detailed Explanation
Duck typing does not prevent a missing method. You find out at call time. An ABC moves that failure to construction: Repository() raises TypeError if get was not implemented. The ABC is a documented contract and a place to put shared helper methods.
You subclass abc.ABC (or use metaclass=ABCMeta) and decorate the required methods with @abstractmethod. Abstract properties and class methods exist too (@property plus @abstractmethod, @classmethod plus @abstractmethod). A subclass becomes concrete when it overrides every abstract name. Instantiating a still-abstract class fails.
isinstance and issubclass honour ABCs. They also honour virtual subclasses: Repository.register(RedisRepository) makes isinstance(redis, Repository) true without inheritance. That is how collections.abc.Sequence accepts tuple — tuple does not inherit from Sequence, it is registered (or recognised by a subclasshook).
__subclasshook__ lets an ABC decide structurally: if the object has __iter__ and __next__, it is an Iterator. Protocols overlap this idea. A Protocol is usually the better choice for type checkers and structural matching. An ABC is the better choice when you want a real base class, shared implementation, and runtime isinstance without @runtime_checkable.
Do not make every class an ABC. If there is only one implementation, a concrete class is enough. If there are many implementations that share no code, a Protocol documents the methods without a forced base. Use an ABC when you have both a contract and some default behaviour, or when you are writing a plugin surface that should fail fast.
collections.abc is the set you should know: Iterable, Iterator, Sequence, Mapping, Set, Callable, Hashable. Implementing __len__ and __getitem__ and inheriting Sequence gives you __contains__, __iter__, count, and index for free.
Code Examples
from abc import ABC, abstractmethod
class Repository(ABC):
@abstractmethod
def get(self, key: str) -> str | None:
raise NotImplementedError
def require(self, key: str) -> str:
value = self.get(key)
if value is None:
raise KeyError(key)
return value
class MemoryRepo(Repository):
def __init__(self) -> None:
self._data: dict[str, str] = {}
def get(self, key: str) -> str | None:
return self._data.get(key)
print(MemoryRepo().get("x")) # None
# Repository() # TypeError: Can't instantiate abstract classfrom collections.abc import Sequence
class Pair(Sequence):
def __init__(self, left: str, right: str):
self._items = (left, right)
def __getitem__(self, index):
return self._items[index]
def __len__(self) -> int:
return 2
print("b" in Pair("a", "b")) # True, from SequenceCommon Gotchas
Forgetting to implement one abstract method
the subclass still looks fine until you instantiate it. The `TypeError` lists the missing names; read it.
`@abstractmethod` on a private helper is unusual
abstract names are the public contract. Keep helpers concrete on the ABC.
`register` lies to `isinstance`
a registered class is not checked for the methods. Register only types you trust.
`raise NotImplementedError` in an abstract method is documentation
the decorator is what blocks instantiation. The raise is for accidental calls via `super`.