abc#
Python’s built-in module for defining Abstract Base Classes and enforcing interface contracts across subclasses.
Basic Usage#
Inherit from ABC and decorate required methods with @abstractmethod. Instantiating the base class directly or failing to override every abstract method in a subclass raises TypeError.
eg.
from abc import ABC, abstractmethod
class Storage(ABC):
@abstractmethod
def save(self, data: bytes) -> None:
...
class LocalStorage(Storage):
def save(self, data: bytes) -> None:
pass
# Storage() -> TypeError: Can't instantiate abstract class Storage
store = LocalStorage()C++ Comparison#
abc.ABC plays the same role as a C++ class containing pure virtual functions, with a key difference in enforcement timing.
| Aspect | C++ Pure Virtual Class | Python abc.ABC |
|---|---|---|
| Syntax | virtual void save() = 0; | class Base(ABC): + @abstractmethod |
| Mechanism | Compiler vtable check | ABCMeta metaclass check |
| Check Timing | Compile time | Runtime at object instantiation |
| Violation Result | Compiler error | TypeError when calling SubClass() |
Pitfalls#
Omitting ABC Inheritance#
Applying @abstractmethod without inheriting from ABC (or setting metaclass=ABCMeta) does not prevent instantiation. Both must be used together.
eg.
from abc import abstractmethod
class BrokenBase:
@abstractmethod
def run(self) -> None:
...
b = BrokenBase() # Succeeds without error because ABC is missingAbstract Properties#
When combining @property and @abstractmethod, place @property as the outer decorator.
eg.
from abc import ABC, abstractmethod
class Resource(ABC):
@property
@abstractmethod
def name(self) -> str:
...