python / expert
Snippet
Structural Subtyping with Protocols
Protocols (PEP 544) enable static duck typing. Unlike standard inheritance, a class is considered a subtype of a Protocol if it simply implements the required methods, without needing to explicitly inherit from the Protocol class.
snippet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
from typing import Protocol, runtime_checkable@runtime_checkableclass Drawable(Protocol):def draw(self) -> str: ...class Circle:def draw(self) -> str: return "Circle drawn"def render(obj: Drawable):if isinstance(obj, Drawable):return obj.draw()return "Not drawable"
Breakdown
1
class Drawable(Protocol):
Defines a template that any object can satisfy by having a 'draw' method.
2
@runtime_checkable
Allows the use of isinstance() at runtime to verify if an object follows the protocol.