Python

Protocol — Structural (Duck) Typing

admin by @admin ADMIN
Jun 18, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Define what an object can DO, not what it IS. A class doesn't need to inherit from a Protocol — it just needs to match the shape. Like TypeScript interfaces with `implements` optional.
Python
Raw
from typing import Protocol

class Closeable(Protocol):
    def close(self) -> None: ...

def safe_use(resource: Closeable) -> None:
    try:
        # ... do work
        pass
    finally:
        resource.close()

class File:
    def close(self): print("file closed")

class Connection:
    def close(self): print("conn closed")

safe_use(File())          # ✓ — has close()
safe_use(Connection())    # ✓ — has close()
# safe_use("hello")        # mypy error — str has no close()
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.