Protocol — structural typing (duck typing).
1from typing import Protocol, runtime_checkable23@runtime_checkable4class Drawable(Protocol):5 def draw(self) -> None: ...67class Circle:8 def draw(self) -> None:9 print("Drawing circle")1011class Square:12 def draw(self) -> None:13 print("Drawing square")1415# Function accepts any object with draw()16def render(shape: Drawable) -> None:17 shape.draw()1819render(Circle()) # OK!20render(Square()) # OK!2122# Type checking23print(isinstance(Circle(), Drawable)) # True2425# Properties26class Comparable(Protocol):27 def __lt__(self, other: "Comparable") -> bool: ...2829def sort(items: list[Comparable]) -> list[Comparable]:30 return sorted(items)
Advantages: