Structural Subtyping with typing.Protocol
`typing.Protocol` implements static duck typing. Any class with matching methods satisfies the protocol automatically without inheriting from a common base class 🦆.
from typing import Protocol
class Drawable(Protocol):
def draw(self) -> str: ...
class Circle:
def draw(self) -> str:
return "Drawing Circle â•"
def render(shape: Drawable):
print(shape.draw())
render(Circle()) # Works without Circle inheriting from Drawable! 🦆
# 92. Structural Subtyping with typing.Protocol `typing.Protocol` implements static duck typing. Any class with matching methods satisfies the protocol automatically without inheriting from a common base class 🦆. ```python from typing import Protocol class Drawable(Protocol): def draw(self) -> str: ... class Circle: def draw(self) -> str: return "Drawing Circle â•" def render(shape: Drawable): print(shape.draw()) render(Circle()) # Works without Circle inheriting from Drawable! 🦆 ``` Protocols embrace the Python philosophy: "If it walks like a duck and quacks like a duck, it's a duck" — but verified at compile time with Mypy! 🦆 --- ### Question How does `typing.Protocol` differ from an Abstract Base Class (`abc.ABC`)? 🧠- [ ] a. Classes satisfy Protocols implicitly by matching methods without explicit inheritance 🦆 - [ ] b. Protocols only work on primitive integer types - [ ] c. Protocols raise runtime errors if called twice - [ ] d. ABCs cannot define abstract methods --- ### Challenge Define `class Greeter(Protocol): def greet(self) -> str: ...`. Create `class Bot:` with `def greet(self) -> str: return 'Hello'`. Call `Bot().greet()` and print output. 🎯 <details> <summary>Solution</summary> ```python from typing import Protocol class Greeter(Protocol): def greet(self) -> str: ... class Bot: def greet(self) -> str: return "Hello" print(Bot().greet()) ``` </details>