Skip to content

Today I Learned 1 min read

TIL - Protocol Classes Enable Structural Typing (Duck Typing with Type Safety)

typing.Protocol lets you define an interface based on structure, not inheritance. Any class that has the required methods satisfies the protocol - no explicit implements needed.

from typing import Protocol

class Drawable(Protocol):
    def draw(self) -> None: ...

class Circle:
    def draw(self) -> None:
        print("Drawing circle")

def render(shape: Drawable) -> None:
    shape.draw()

render(Circle())  # no inheritance required
python