Python Classes and Objects · Lesson 90 of 149

Python Abstract Base Classes

What you will learn

  • The problem with NotImplementedError, and how abstract base classes fix it
  • ABC and @abstractmethod
  • Abstract properties and class methods
  • The template method pattern
  • The ready-made classes in collections.abc
  • register and __subclasshook__, and when to use all this

1. A contract for subclasses

In lesson 13.5, a base class marked a method that subclasses must write by raising NotImplementedError:

class Animal:
    def speak(self):
        raise NotImplementedError

a = Animal()
print(type(a).__name__)
Animal

The object was created without complaint, and the mistake shows up only when speak() is called, possibly much later, in the middle of a program. An abstract base class (ABC) makes the mistake appear at once, when you try to create the object.

Quick check: when does `NotImplementedError` appear, and when would an abstract class complain?

NotImplementedError appears only when the method is called. An abstract class complains when you try to create an object that is missing the method.

2. ABC and @abstractmethod

Import ABC and abstractmethod from the abc module. Make your class inherit from ABC, and mark the required methods with @abstractmethod:

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        ...

    @abstractmethod
    def perimeter(self):
        ...

    def describe(self):
        return f"{type(self).__name__}: area {self.area():.1f}, perimeter {self.perimeter():.1f}"

(The three dots ... are a valid way to write an empty body.) The class is now abstract: it cannot be instantiated.

Shape()
TypeError: Can't instantiate abstract class Shape without an implementation for abstract methods 'area', 'perimeter'

A subclass must override every abstract method to become concrete, and then it works:

class Rect(Shape):
    def __init__(self, w, h):
        self.w, self.h = w, h

    def area(self):
        return self.w * self.h

    def perimeter(self):
        return 2 * (self.w + self.h)

class Circle(Shape):
    def __init__(self, r):
        self.r = r

    def area(self):
        return 3.14159 * self.r ** 2

    def perimeter(self):
        return 2 * 3.14159 * self.r

print(Rect(2, 3).describe())
print(Circle(1).describe())
Rect: area 6.0, perimeter 10.0
Circle: area 3.1, perimeter 6.3

A subclass that forgets one is still abstract, and the error names the missing method:

class Half(Shape):
    def area(self):
        return 1

Half()
TypeError: Can't instantiate abstract class Half without an implementation for abstract method 'perimeter'

So the contract is enforced: if you can create an object of a subclass, it has everything the base class required. Notice that describe is a normal method written once in the base class, using the abstract area and perimeter: every subclass gets it for free.

You can inspect the contract:

print(sorted(Shape.__abstractmethods__))
print(Rect.__abstractmethods__)
print(isinstance(Rect(1, 1), Shape), issubclass(Circle, Shape))
['area', 'perimeter']
frozenset()
True True

3. A body in an abstract method

An abstract method may have a body. A subclass must still override it, but can call it with super() to reuse the default (lesson 13.6):

class Plugin(ABC):
    @abstractmethod
    def run(self, data):
        return "default behaviour"

class P1(Plugin):
    def run(self, data):
        return super().run(data) + " + extra"

print(P1().run(1))
default behaviour + extra

4. Abstract properties and class methods

Other kinds of members can be abstract too. When stacking decorators, @abstractmethod goes innermost, that is, closest to the def:

class Base(ABC):
    @property
    @abstractmethod
    def name(self):
        ...

    @classmethod
    @abstractmethod
    def create(cls):
        ...

    @staticmethod
    @abstractmethod
    def helper():
        ...

class Impl(Base):
    @property
    def name(self):
        return "impl"

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

    @staticmethod
    def helper():
        return 1

i = Impl.create()
print(i.name, Impl.helper(), isinstance(i, Base))
impl 1 True

The subclass must supply a real property, class method and static method with these names.

5. The template method pattern

A base class can write the overall steps of a job as a normal method, and leave the individual steps abstract. Each subclass fills in the steps. This is the template method pattern:

class Template(ABC):
    def run(self):
        return [self.step1(), self.step2(), "done"]

    @abstractmethod
    def step1(self):
        ...

    @abstractmethod
    def step2(self):
        ...

class Concrete(Template):
    def step1(self):
        return "one"

    def step2(self):
        return "two"

print(Concrete().run())
['one', 'two', 'done']

The order of the steps is fixed in the base class, and the subclasses decide what each step does.

6. Ready-made ABCs: collections.abc

Python's standard library has a whole family of ABCs describing the common kinds of container, in collections.abc: Sized, Iterable, Iterator, Container, Sequence, Mapping, MutableMapping, Callable, Hashable and more. They have two uses.

Use 1: testing what an object can do

isinstance against these classes asks "does it behave like this?", and it works by checking for the methods, not by inheritance:

from collections.abc import Sized, Iterable, Sequence, Mapping, Callable, Hashable

print(isinstance([], Sized), isinstance(5, Sized))
print(isinstance({}, Mapping), isinstance([], Sequence), isinstance("a", Sequence))
print(isinstance(len, Callable), isinstance([], Hashable), isinstance((1,), Hashable))

class Bag:
    def __len__(self):
        return 3

print(isinstance(Bag(), Sized), isinstance(Bag(), Iterable))
True False
True True True
True False True
True False

Bag does not inherit from Sized, but it has __len__, so it counts as Sized. It has no __iter__, so it is not Iterable. This is duck typing with a name (lesson 13.6): prefer isinstance(x, Iterable) to a test for list, so that all collections are accepted.

Use 2: getting methods for free

If you inherit from Mapping or Sequence and write only the few required methods, you get many others automatically:

from collections.abc import Mapping, Sequence

class MyMap(Mapping):
    def __init__(self, d):
        self._d = d

    def __getitem__(self, k):
        return self._d[k]

    def __iter__(self):
        return iter(self._d)

    def __len__(self):
        return len(self._d)

m = MyMap({"a": 1, "b": 2})
print(m["a"], len(m), list(m), "a" in m)
print(m.get("z", 0), list(m.items()), list(m.values()))
print(m == {"a": 1, "b": 2})
1 2 ['a', 'b'] True
0 [('a', 1), ('b', 2)] [1, 2]
True

Only three methods were written (__getitem__, __iter__, __len__), yet in, get, items, values, keys and == all work. The same goes for Sequence:

class MySeq(Sequence):
    def __init__(self, *v):
        self._v = v

    def __getitem__(self, i):
        return self._v[i]

    def __len__(self):
        return len(self._v)

ms = MySeq(3, 1, 4, 1)
print(len(ms), ms[0], list(ms), 4 in ms)
print(ms.index(4), ms.count(1), list(reversed(ms)), ms[1:3])
4 3 [3, 1, 4, 1] True
2 2 [1, 4, 1, 3] (1, 4)

With just __getitem__ and __len__, you get index, count, in, iteration and reversed. Use these classes when you build your own collection types.

7. register and subclasshook

Sometimes a class cannot inherit from your ABC (it is in a library), but you want isinstance to accept it. Two tools:

  • ABC.register(Class) declares a class a "virtual subclass" without inheritance:
class Virtual(ABC):
    pass

Virtual.register(int)
print(isinstance(5, Virtual), issubclass(int, Virtual))
True True
  • __subclasshook__ lets the ABC decide by itself whether a class qualifies, for example by checking for a method. This is how Sized accepts any class with __len__:
class Duck(ABC):
    @abstractmethod
    def quack(self):
        ...

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Duck:
            return hasattr(C, "quack") or NotImplemented
        return NotImplemented

class Quacker:
    def quack(self):
        return "Quack"

print(isinstance(Quacker(), Duck), issubclass(Quacker, Duck), isinstance(5, Duck))
True True False

Quacker never mentioned Duck, yet it counts as one, because it has quack. These are advanced tools; most programs never need them.

8. When to use an ABC

Situation Choose
a family of classes that must all provide certain methods, and you want the mistake caught early an ABC with @abstractmethod
a template method whose steps vary an ABC
you are building a collection type inherit from collections.abc classes
unrelated classes that just share method names duck typing, no ABC needed
you only want to document a shape for tools and type checkers a Protocol (lesson 19.2)
a base class with no abstract methods a normal class (an ABC without abstract methods can still be created)

Do not overuse them: small programs rarely need an ABC. They pay off in larger designs, such as plugins, where different people write the subclasses.

Worked example: exporters with a fixed template

A program saves rows (dictionaries) in several formats. The steps are the same: a start, a line per row, a join and an end. Only how a row is formatted differs, and that is abstract. A format that forgets it cannot even be created.

import json
from abc import ABC, abstractmethod


class Exporter(ABC):
    extension = ""

    def export(self, rows):
        header = self.start(rows)
        body = [self.format_row(r) for r in rows]
        return header + self.join(body) + self.end()

    def start(self, rows):
        return ""

    def end(self):
        return ""

    def join(self, parts):
        return "\n".join(parts)

    @abstractmethod
    def format_row(self, row):
        ...


class CsvExporter(Exporter):
    extension = ".csv"

    def start(self, rows):
        return ",".join(rows[0]) + "\n" if rows else ""

    def format_row(self, row):
        return ",".join(str(v) for v in row.values())


class JsonLinesExporter(Exporter):
    extension = ".jsonl"

    def format_row(self, row):
        return json.dumps(row)


class Broken(Exporter):
    extension = ".x"


rows = [{"name": "Rina", "age": 25}, {"name": "Sam", "age": 22}]
for cls in (CsvExporter, JsonLinesExporter):
    print(cls.__name__, cls.extension)
    print(cls().export(rows))

try:
    Broken()
except TypeError as err:
    print("TypeError:", err)

registry = {c.extension: c for c in Exporter.__subclasses__() if not c.__abstractmethods__}
print(sorted(registry))
CsvExporter .csv
name,age
Rina,25
Sam,22
JsonLinesExporter .jsonl
{"name": "Rina", "age": 25}
{"name": "Sam", "age": 22}
TypeError: Can't instantiate abstract class Broken without an implementation for abstract method 'format_row'
['.csv', '.jsonl']
Part Role
export the template: fixed order of steps, written once
start, end, join optional hooks with defaults; subclasses may override
format_row abstract: every format must provide it
Broken() refused at creation, naming the missing method
registry a plug-in table built from the concrete subclasses (those with no abstract methods left)

A new format is one new class; the rest of the program is untouched. The names and ages are made up.

Common mistakes

  • Forgetting to inherit from ABC. Without it, @abstractmethod has no effect and the class can still be created.
  • Putting @abstractmethod outside @property or @classmethod. It must be the innermost decorator.
  • Using an ABC when duck typing or a plain base class is enough.
  • Testing isinstance(x, list) when isinstance(x, Sequence) or Iterable would accept more.
  • Expecting an ABC with no abstract methods to be abstract. It can be instantiated.
  • Forgetting that a subclass missing one method is still abstract.

Key takeaways

  • class Shape(ABC) plus @abstractmethod makes subclasses implement the required methods; creating an incomplete one fails immediately with a clear TypeError.
  • Abstract classes can also hold normal methods (including the template method pattern) and abstract properties, class methods and static methods (decorator order: @abstractmethod innermost).
  • collections.abc offers Sized, Iterable, Sequence, Mapping and more: use them for isinstance tests, or inherit from Sequence and Mapping to get many methods for free.
  • register and __subclasshook__ let unrelated classes count as subclasses.
  • Use ABCs for larger designs with several implementers; use duck typing or protocols when nothing needs enforcing.

Practice

1. What happens when you call Shape() for an abstract Shape?

Show answer

TypeError: Can't instantiate abstract class Shape without an implementation for abstract methods ...

2. What must a subclass do to become concrete?

Show answer

Override every abstract method of its parent(s). If even one is missing, it stays abstract and cannot be instantiated.

3. In which order do you write @property and @abstractmethod?

Show answer

@property first (outer), then @abstractmethod (inner, closest to the def).

4. Why does isinstance(Bag(), Sized) work for a class that never mentions Sized?

Show answer

Sized decides membership by checking for a __len__ method (through __subclasshook__), so any class with __len__ counts.

5. Which three methods must you write to build a read-only dictionary-like class from Mapping?

Show answer

__getitem__, __iter__ and __len__. The class then gets get, items, keys, values, in and == for free.

6. What is the template method pattern?

Show answer

A base class writes the overall sequence of steps in one normal method, and leaves some steps abstract, so subclasses fill in the details without changing the order.