PythiloLesson 14 of 30 · progress kept in this browser

Abstract base classes

A protocol describes a shape from the outside. An abstract base class, or ABC, is a real parent class that subclasses must complete. Python refuses to create an instance while any abstract method is still missing.

from abc import ABC, abstractmethod

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

    def describe(self):
        return f"area {self.area():.1f}"

class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side ** 2

print(Square(3).describe())
try:
    Shape()
except TypeError as e:
    print(e)
  • The error comes when the object is created, not later when the missing method is finally called.
  • Ordinary methods such as describe are inherited and may call the abstract ones.
  • collections.abc has ABCs for containers. Subclass Mapping, write __getitem__, __len__ and __iter__, and you get get, keys, items, in and == for free.

Use an ABC when subclasses should share code and must fill in specific methods. Use a protocol when unrelated classes only need to match a shape.

Your task

Make Storage an abstract base class with abstract load(key) and save(key, value), keeping its concrete update(key, fn), which saves fn(old value) and returns it. MemoryStorage(Storage) keeps values in a dict, and its load raises KeyError for a missing key.