Protocols in Python
Structural typing: anything with the right methods satisfies the protocol.
from typing import Protocol, runtime_checkable
@runtime_checkable
class Sized(Protocol):
def __len__(self) -> int:
...
class Tour:
def __init__(self, steps):
self.steps = steps
def __len__(self):
return len(self.steps)
def describe(item: Sized) -> str:
return f"{len(item)} items"
print(describe([1, 2, 3]), describe(Tour([1, 2])))
print(isinstance(Tour([]), Sized), isinstance(3, Sized))
How it works
- No inheritance is required, only matching methods.
runtime_checkableallows isinstance against it.- This is how duck typing gets a name a checker understands.
Keywords and builtins used here
SizedTourclassdefdescribeintisinstancelenprintreturnselfstr
The run, in numbers
- Lines
- 23
- Characters to type
- 397
- Tokens
- 121
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 66 seconds.
Step 2 of 4 in Typing in depth, step 42 of 53 in Pythonic Python.