Python Reference ยท Standard Library: Data Structures and Functional Tools
The abc module
Reference for Python's abc module: ABC, @abstractmethod, abstract properties, register() for virtual subclasses and the collections.abc interfaces.
The abc module lets you define abstract base classes: classes that describe an interface and refuse to be instantiated until a subclass provides every required method. This turns "you forgot to implement area()" from a surprise deep in the program into an immediate TypeError when you create the object.
You write an abstract class by inheriting from ABC and marking required methods with @abstractmethod. Abstract classes can still contain normal methods with real code, so they work well as templates that share behavior while leaving a few steps to subclasses.
from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self) -> float: ...
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
What is in the module
| Name | Description |
|---|---|
ABC |
Convenience base class; its metaclass is ABCMeta. Inherit from it to make an abstract class. |
ABCMeta |
The metaclass that tracks abstract methods and virtual subclasses. Use metaclass=ABCMeta when you need another metaclass setup. |
@abstractmethod |
Marks a method that subclasses must override. Works with @property, @classmethod and @staticmethod (put @abstractmethod innermost). |
register(subclass) |
Class method on an ABC: declares subclass a virtual subclass. It can also be used as a decorator. |
__subclasshook__(C) |
Class method an ABC can define to decide issubclass() results. Returns True, False or NotImplemented. |
get_cache_token() |
Returns a token that changes whenever any ABC is registered. Rarely needed. |
update_abstractmethods(cls) |
Recomputes the abstract set after you add methods dynamically (3.10). |
Raises: TypeError when you instantiate a class that still has abstract methods.
Usage notes
- The check happens at instantiation, not at class definition. A subclass that does not override every abstract method is itself abstract, and only creating an instance fails.
- Abstract methods can have a body. Subclasses may call
super().method()to reuse it. A docstring,...orpassis enough when there is nothing to share. - An abstract class needs
ABCorABCMeta. Using@abstractmethodin a plain class has no effect. - Overriding an abstract property with an attribute works, as
Savings.balance = 100shows, because the name is simply defined. register()does not add methods or check anything. The registered class is trusted. The ABC does not appear in the registered class's__mro__, andsuper()calls do not reach it.isinstance()against ABCs can be slow-ish compared with plain classes, because of caching and hooks. This rarely matters.- Use
collections.abcfor built-in interfaces:Iterable,Iterator,Sequence,Mapping,MutableMapping,Callable,Hashable,Sized,Containerand more. Inheriting from them gives you mixin methods for free; for example, a class that defines__getitem__and__len__and inherits fromSequencealso getsindex(),count(),__contains__and__iter__. - Protocols are the structural alternative.
typing.Protocoldescribes an interface without inheritance and is checked by type checkers; ABCs enforce at runtime. - Do not overuse them. In Python, duck typing is the default; reach for an ABC when you publish a base class for others to extend or need early errors.