Abstract Base Classes (abc)

Published by Brayan K

An abstract base class is a class you can't instantiate directly — it declares methods that every subclass must implement, and Python enforces that contract by raising a TypeError if a subclass leaves any of them out.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Abstractness blocks construction of an incomplete class

Inheriting from ABC supplies the machinery, but a class is only abstract while it has unimplemented abstract members. A class that merely inherits ABC can still be constructed. The useful contract is specific: name the operation that concrete subclasses must provide, then test the concrete behavior separately.

from abc import ABC, abstractmethod

class Parser(ABC):
    @abstractmethod
    def parse(self, text):
        pass

class Words(Parser):
    def parse(self, text):
        return text.split()

print(Words().parse("red blue"))
print(sorted(Parser.__abstractmethods__))
print(sorted(Words.__abstractmethods__))

# ✅ Expected output:
# ['red', 'blue']
# ['parse']
# []

The abstract class defines the required operation; Words supplies the implementation. The stored abstract-method names explain why one class is incomplete and the other is constructible. Basic overriding and inherited method lookup belong to Inheritance and Polymorphism.

from abc import ABC, abstractmethod

class Parser(ABC):
    @abstractmethod
    def parse(self, text):
        pass

class Missing(Parser):
    pass

try:
    Missing()
except TypeError as error:
    print(type(error).__name__)
    print("Missing:", ", ".join(sorted(Missing.__abstractmethods__)))

# ✅ Expected output:
# TypeError
# Missing: parse

The constructor raises TypeError before an instance is returned. Python versions phrase that traceback differently; this example reports its type and the missing names, which identify the same defect. Implement the missing member on the subclass rather than trying to call it on an object that was never created.

ABC alone and abstractmethod alone are different pieces

from abc import ABC, abstractmethod

class PlainBase(ABC):
    pass

class MarkerOnly:
    @abstractmethod
    def run(self):
        pass

print(isinstance(PlainBase(), PlainBase))
print(isinstance(MarkerOnly(), MarkerOnly))
print(MarkerOnly().run())

# ✅ Expected output:
# True
# True
# None

The first class has no required abstract members. The second marks a function but does not use ABC’s metaclass machinery. Neither construction is rejected. Do not judge enforcement from the presence of a decorator alone; the base class arrangement matters too.

An override can satisfy the name while breaking the interface

from abc import ABC, abstractmethod

class Reader(ABC):
    @abstractmethod
    def read(self, key):
        pass

class WrongReader(Reader):
    def read(self):
        return "ready"

reader = WrongReader()
reader.read("settings")

# ✅ Expected error:
# TypeError: WrongReader.read() takes 1 positional argument but 2 were given

WrongReader is constructible because it replaces read, but its method cannot accept the argument promised by the base interface. ABC also does not prove a return type, useful result or correct algorithm. Exercise implementations with behavioral tests; use Advanced Type Hints (Generics, Protocol, TypedDict) for static interface checking.

from abc import ABC, abstractmethod

class Job(ABC):
    @abstractmethod
    def run(self):
        pass

class Placeholder(Job):
    def run(self):
        pass

job = Placeholder()
print(sorted(Placeholder.__abstractmethods__))
print(job.run())

# ✅ Expected output:
# []
# None

The placeholder returns None because that is what its implementation does. Abstractness tracks the requirement to override; it is not a test of whether the resulting work is useful. Keep these two checks separate when designing a plugin system.

Put abstractmethod closest to the function

from abc import ABC, abstractmethod

class Factory(ABC):
    @abstractmethod
    @classmethod
    def create(cls):
        pass

# ✅ Expected error:
# AttributeError: attribute '__isabstractmethod__' of 'classmethod' objects is not writable

The outer abstractmethod tries to mark an already-created classmethod object. Use classmethod on the outside and abstractmethod next to the function instead. The same placement rule applies when combining an abstract property with property.

from abc import ABC, abstractmethod

class Factory(ABC):
    @classmethod
    @abstractmethod
    def create(cls):
        pass

class Label(Factory):
    def __init__(self, text):
        self.text = text

    @classmethod
    def create(cls):
        return cls("draft")

print(Label.create().text)
print(sorted(Label.__abstractmethods__))

# ✅ Expected output:
# draft
# []

Registration changes membership checks, not implementation

from abc import ABC, abstractmethod

class Reader(ABC):
    @abstractmethod
    def read(self):
        pass

class Legacy:
    pass

Reader.register(Legacy)
item = Legacy()
print(isinstance(item, Reader))
print(issubclass(Legacy, Reader))
print(hasattr(item, "read"))
print(Reader in Legacy.__mro__)

# ✅ Expected output:
# True
# True
# False
# False

Registering a class is an assertion you make about compatibility. It does not supply missing behavior, change the inheritance chain, or prevent constructing the registered class. Use real inheritance when you want inherited implementations and ordinary abstract-member enforcement. Use registration only when you have separately established the interface.

Complete a concrete formatter

Fill the abstract base, the abstract marker and the concrete string operation. Both the abstract method and the implementation should accept the same text argument. The final line confirms that no abstract members remain.

from abc import ABC, abstractmethod

class Formatter(___):
    @___
    def format(self, text):
        pass

class Uppercase(Formatter):
    def format(self, text):
        return text.___()

print(Uppercase().format("ready"))
print(sorted(Uppercase.__abstractmethods__))

# 👉 replace ___ with ABC
# 👉 replace ___ with abstractmethod
# 👉 replace ___ with upper

# ✅ Expected output:
# READY
# []

Build two renderers behind the same interface

Define an abstract Renderer with render(self, words). Implement CommaRenderer and LineRenderer: one joins a list of words with comma-space, and the other joins it with a vertical bar. Call both through the same render_report function using red and blue. Keep formatting behavior in the concrete classes, and print the abstract-member sets to show that each is concrete. Do not use register to bypass implementation.

from abc import ABC, abstractmethod

class Renderer(ABC):
    @abstractmethod
    def render(self, words):
        pass

class CommaRenderer(Renderer):
    def render(self, words):
        return ", ".join(words)

class LineRenderer(Renderer):
    def render(self, words):
        return " | ".join(words)

def render_report(renderer, words):
    return renderer.render(words)

for renderer in [CommaRenderer(), LineRenderer()]:
    print(render_report(renderer, ["red", "blue"]))
    print(sorted(type(renderer).__abstractmethods__))

# ✅ Expected output:
# red, blue
# []
# red | blue
# []

The shared caller relies on a compatible operation, not on knowing which formatter it received. ABC construction checks complement that design; expected output tests still establish what each renderer actually does.

Practice quiz

What does this program print? from abc import ABC class Base(ABC): pass print(isinstance(Base(), Base))

  • False
  • TypeError
  • True
  • None

Answer: True. With no abstract members left, an ABC subclass is concrete.

What does this program print? from abc import ABC, abstractmethod class Base(ABC): @abstractmethod def run(self): pass print(sorted(Base.__abstractmethods__))

  • ['run']
  • []
  • ['Base']
  • ['__init__']

Answer: ['run']. The marker records run as a required abstract member.

What does this program print? from abc import ABC, abstractmethod class Base(ABC): @abstractmethod def run(self): pass class Child(Base): def run(self): pass print(Child().run())

  • TypeError
  • True
  • []
  • None

Answer: None. An ordinary placeholder override is concrete even though it returns None.

Which decorator should be closest to the function for an abstract class method?

  • classmethod
  • abstractmethod
  • staticmethod
  • property

Answer: abstractmethod. Apply the abstract marker to the function before wrapping it as a classmethod.

What does this program print? from abc import ABC class Base(ABC): def run(self): return "ready" class Legacy: pass Base.register(Legacy) print(isinstance(Legacy(), Base)) print(hasattr(Legacy(), "run"))

  • True False
  • True True
  • False False
  • False True

Answer: True False. Virtual membership does not copy the base method.

What does a concrete override still need besides clearing the abstract-method marker?

  • A different method name
  • Registration on every call
  • Compatible parameters and tested behavior
  • A global variable

Answer: Compatible parameters and tested behavior. ABC does not prove parameter compatibility or useful semantics.

What does this program print? from abc import abstractmethod class Loose: @abstractmethod def run(self): return "called" print(Loose().run())

  • TypeError
  • called
  • None
  • False

Answer: called. Without ABC machinery, the abstract marker alone does not block construction.

When is an incomplete ordinary ABC subclass rejected?

  • When the module is imported in every case
  • When its source file is saved
  • Only after its abstract method runs
  • When an instance is constructed

Answer: When an instance is constructed. The usual enforcement point is constructing the class while abstract members remain.

Continue this course

Related lessons