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.

AspectC++ Pure Virtual ClassPython abc.ABC
Syntaxvirtual void save() = 0;class Base(ABC): + @abstractmethod
MechanismCompiler vtable checkABCMeta metaclass check
Check TimingCompile timeRuntime at object instantiation
Violation ResultCompiler errorTypeError 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 missing

Abstract 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:
        ...