typestar

Abstract base classes in Python

ABCs state the interface and refuse to instantiate until it is met.

from abc import ABC, abstractmethod


class Check(ABC):
    @abstractmethod
    def passes(self, text: str) -> bool:
        ...

    def describe(self) -> str:
        return f"{type(self).__name__.lower()} check"


class MinLength(Check):
    def __init__(self, floor):
        self.floor = floor

    def passes(self, text):
        return len(text) >= self.floor


print(MinLength(3).passes("ada"), MinLength(3).describe())
try:
    Check()
except TypeError as exc:
    print(str(exc)[:48])

How it works

  1. abstractmethod marks what a subclass must provide.
  2. Instantiating an incomplete subclass raises TypeError.
  3. A concrete method in the ABC is shared behavior.

Keywords and builtins used here

The run, in numbers

Lines
25
Characters to type
434
Tokens
136
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 74 seconds.

Type this snippet

Step 1 of 3 in Class machinery, step 35 of 53 in Pythonic Python.

← Previous Next →