Protocols in Python
Structural typing: duck typing the type checker understands.
from typing import Protocol
class Drawable(Protocol):
def draw(self) -> str: ...
class Circle:
def draw(self) -> str:
return "( )"
class Square:
def draw(self) -> str:
return "[ ]"
def render(shapes: list[Drawable]) -> str:
return " ".join(s.draw() for s in shapes)
How it works
- A
Protocollists the methods a type must have. CircleandSquarematch it without inheriting.renderaccepts anything shaped likeDrawable.
Keywords and builtins used here
CircleDrawableSquareclassdefdrawforlistrenderreturnselfstr
The run, in numbers
- Lines
- 19
- Characters to type
- 273
- Tokens
- 84
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 48 seconds.
Step 5 of 5 in Protocols & context managers, step 19 of 53 in Pythonic Python.