On this page
abc
Up: stdlib_module | Next: annotationlib
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — abc
Tags: #public #python3 #stdlib
Import
import abc
Overview
Abstract Base Classes (ABC, @abstractmethod) for defining explicit inheritance contracts that fail fast at instantiation time if a subclass omits required methods. Reach for abc.ABC when you want nominal inheritance with shared helper methods; prefer typing.Protocol (in typing) when you want structural duck typing without forcing subclasses to inherit from a base class.
Quick Start
from abc import ABC, abstractmethod
class Storage(ABC):
@abstractmethod
def get(self, key: str) -> str | None: ...
class MemoryStorage(Storage):
def __init__(self) -> None:
self._data: dict[str, str] = {}
def get(self, key: str) -> str | None:
return self._data.get(key)
store = MemoryStorage()
assert store.get("missing") is None
Implementation Walkthrough
1. Abstract Properties, Classmethods & Shared Template Methods
When combining @abstractmethod with @property, @classmethod, or @staticmethod, always place @abstractmethod as the innermost decorator:
from abc import ABC, abstractmethod
class Formatter(ABC):
@property
@abstractmethod
def extension(self) -> str: ...
@abstractmethod
def render(self, data: dict[str, object]) -> str: ...
def filename(self, stem: str) -> str:
return f"{stem}.{self.extension}"
2. Registering Virtual Subclasses (ABC.register)
Register third-party classes without modifying them so isinstance() / issubclass() returns True:
from abc import ABC
class Printable(ABC):
pass
Printable.register(str)
assert isinstance("hello", Printable)
Gotchas & Boundaries
@abstractmethodonly works if the class inherits fromABC(or setsmetaclass=ABCMeta): WithoutABC, Python silently allows instantiating incomplete subclasses.@abstractmethodmust be the innermost decorator: Writing@abstractmethodabove@propertyor@classmethodbreaks descriptor binding.- Virtual subclasses via
.register()are NOT checked for method implementation:isinstance()returnsTrue, but missing methods won't fail until called.
Common Functions
- abc.abstractmethod() —
abstractmethod(funcobj)— A decorator indicating abstract methods. - abc.get_cache_token() —
get_cache_token()— Returns the current ABC cache token. - abc.update_abstractmethods() —
update_abstractmethods(cls)— Recalculate the set of abstract methods of an abstract class.
Classes & Objects
- abc.ABC — Helper class that provides a standard way to create an ABC using inheritance.
- abc.ABCMeta — Metaclass for defining Abstract Base Classes (ABCs). (Methods:
.mro(),.register()) - abc.abstractclassmethod — A decorator indicating abstract classmethods.
- abc.abstractproperty — A decorator indicating abstract properties. (Methods:
.deleter(),.getter(),.setter()) - abc.abstractstaticmethod — A decorator indicating abstract staticmethods.
Linked from
Related notes
- tuts/python3/stdlib_module/annotationlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/abc/ABC Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/abc/ABCMeta Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/abc/abstractclassmethod Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/abc/abstractmethod Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/abc/abstractproperty Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/abc/abstractstaticmethod Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/abc/get_cache_token Linked here; shared tags: #stdlib