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
abstractmethodmarks what a subclass must provide.- Instantiating an incomplete subclass raises TypeError.
- A concrete method in the ABC is shared behavior.
Keywords and builtins used here
CheckMinLengthasboolclassdefdescribeexceptlenpassesprintreturnselfstrtrytype
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.
Step 1 of 3 in Class machinery, step 35 of 53 in Pythonic Python.