On this page
  1. abc
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Abstract Properties, Classmethods & Shared Template Methods
  7. 2. Registering Virtual Subclasses (ABC.register)
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

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

Common Functions

Classes & Objects

Linked from

Related notes