Protocols (Structural Typing)
PY · Classes & OOPsyntax
from typing import Protocol
class Drawable(Protocol):
def draw(self) -> None: ...example
from typing import Protocol
class Saveable(Protocol):
def save(self, path: str) -> None: ...
class Document:
def save(self, path: str) -> None:
print(f"Saved to {path}")
def backup(item: Saveable, dest: str) -> None:
item.save(dest)
backup(Document(), "/tmp/doc.txt")output
Saved to /tmp/doc.txtNote Protocols enable duck-typing with static type checking. Classes do not need to explicitly inherit from the Protocol; they just need matching methods.