the full guide

Abstraction and ABCs

Abstraction means exposing what something does and hiding how. An Abstract Base Class (ABC) defines methods that subclasses must implement, and can't itself be instantiated. A Protocol describes a required shape without any inheritance.

6 min Intermediate

What you need: The earlier topics of this module.

Definition

Abstraction means exposing what something does and hiding how. An Abstract Base Class (ABC) defines methods that subclasses must implement, and can't itself be instantiated. A Protocol describes a required shape without any inheritance.

In simple words

A car's steering wheel hides the engine. An ABC is a contract: anything calling itself a Vehicle must have a drive() method, or Python refuses to create it.

Why it matters

It catches missing methods when an object is created, rather than much later. It also lets you swap one model or database for another without changing the code that calls it.

How it works

In code

abstract.py
from abc import ABC, abstractmethod

class Model(ABC):
    @abstractmethod
    def predict(self, x):
        ...

class AlwaysYes(Model):
    def predict(self, x):
        return "yes"

class Broken(Model):
    pass

print(AlwaysYes().predict(1))

for cls in (Model, Broken):
    try:
        cls()
    except TypeError as error:
        print(cls.__name__, "can't be created:", "abstract" in str(error))

Output

yes
Model can't be created: True
Broken can't be created: True

Common mistakes

  • Forgetting to inherit from ABC, so that @abstractmethod has no effect.
  • Building big class hierarchies too early. Add abstraction once you have two real cases.

Check yourself

Question 1

1. Can you create an object of an ABC with abstract methods?

Question 2

2. What must a subclass do?

Summary

  • Abstraction hides how, and shows what.
  • ABCs enforce required methods.

Finished reading?

Sources: Python docs: abc