Skip to content

8 - Static duck typing via Protocol

Protocol is a good fit for use cases which only care about the behaviour and/or attributes of an object, not the actual type of the object. Protocols are great for defining interfaces, also in cases where (abstract) base classes are out of question. Available in Python 3.8+.


Read more
The code
import typing
import uuid
from dataclasses import dataclass

class InstanceWithId(typing.Protocol):
    def id(self) -> str:

def print_instance_id(instance: InstanceWithId) -> None:
    print(f"Received instance with id: {}")

class MyDataClass:
    id: str

class MyRegularClass:
    def __init__(self) -> None: = str(uuid.uuid4())

class MyNamedTuple(typing.NamedTuple):
    id: str

class ClassWithoutId:

print_instance_id(ClassWithoutId())  # mypy gives error