Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

abc — abstract base classes

The abc module lets you define abstract base classes and mark methods as abstract.

Version: Python 3.14; repository image, production runtime not attested

Syntax

import abc

class Interface(abc.ABC):
    @abc.abstractmethod
    def operation(self):
        ...

abc provides abstract base classes. Inheriting from abc.ABC uses the abc.ABCMeta metaclass; the @abc.abstractmethod decorator alone is insufficient without that metaclass.

When instance creation goes through object.__new__, it raises TypeError if the class still has abstract methods. In CPython, an abstract base class that inherits from list can still be instantiated even if it has abstract methods, because the list constructor skips that check. An abstract method may contain an implementation callable through super(). When combining it with @property, @classmethod, or @staticmethod, place @abc.abstractmethod closest to def.

register() registers a virtual subclass for issubclass() and isinstance(), but neither supplies methods nor enforces implementation of abstract methods.

Examples

import abc


class Reader(abc.ABC):
    @abc.abstractmethod
    def read(self):
        ...


class TextReader(Reader):
    def read(self):
        return "hello"


try:
    Reader()
except TypeError:
    print("abstract")

reader = TextReader()
print(reader.read())
print(isinstance(reader, Reader))

Result

abstract
hello
True

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources