Duck Typing for the Type Checker: Python's typing.Protocol in Depth
This article examines typing.Protocol beyond the basics: attribute and property members, explicit subclassing with default methods, callback and generic protocols, and what runtime_checkable can and cannot verify since Python 3.12.
Python code has long relied on duck typing, the practice of accepting any object that offers the required methods regardless of its class, and type hints seemed at first to contradict it by naming concrete classes. The present article addresses typing.Protocol, introduced in Python 3.8 by PEP 544, which lets a type checker accept any class whose members match a declared interface, without any inheritance. A protocol was introduced briefly in an earlier article of this series; the present one examines what that introduction left aside: attribute and property members, explicit subclassing with default methods, callback and generic protocols, and the precise, and limited, behaviour of runtime_checkable since Python 3.12. Describing an interface once and letting every compatible class satisfy it without knowing that the interface exists is the secret weapon of typing.Protocol.
Members of a Protocol
A protocol is a class that derives from Protocol and lists its members: methods with their signatures, variables declared with annotations and read-only values declared as properties. The typing specification states that a class is compatible with a protocol only if it implements every member with compatible types, so a static checker compares names and signatures, whereas the interpreter itself ignores the protocol unless it is asked to check it. A class may also subclass a protocol explicitly; this is not necessary for type checking, but it lets the class inherit default implementations written in the protocol.
from typing import Protocol
class Greeter(Protocol):
language: str
def name(self) -> str: ...
def greet(self) -> str:
return f"[{self.language}] hello, {self.name()}"
class English(Greeter):
language = "en"
def name(self) -> str:
return "Ada"
class Spanish:
language = "es"
def name(self) -> str:
return "Grace"
def welcome(person: Greeter) -> str:
return person.name()
print(English().greet()) # Output: [en] hello, Ada
print(welcome(English()), welcome(Spanish())) # Output: Ada Grace
try:
Greeter()
except TypeError as error:
print(error) # Output: Protocols cannot be instantiated
The class English subclasses the protocol and inherits greet, while Spanish never mentions it and is still accepted by welcome, both by a type checker and at run time; only the explicit subclass, however, receives the default method, because a structural match copies nothing. An instance attribute assigned only inside a method is not a protocol member under the specification, so attributes must be declared in the class body. When a family of classes shares substantial code, the abstract base classes described in the article devoted to abstract base classes remain the more explicit tool.
Callback and Generic Protocols
A protocol whose only member is __call__ describes a callable more precisely than Callable, which cannot express keyword arguments, defaults or overloads. Protocols can also be generic, and since Python 3.12 the type parameter is declared directly in the class statement, so a single protocol describes, for example, any container from which values of one type can be read.
from typing import Protocol
class Formatter(Protocol):
def __call__(self, value: float, *, digits: int = 2) -> str: ...
def report(values: list[float], fmt: Formatter) -> list[str]:
return [fmt(v, digits=1) for v in values]
def fixed(value: float, *, digits: int = 2) -> str:
return f"{value:.{digits}f}"
class Source[T](Protocol):
def read(self) -> T: ...
class Sensor:
def read(self) -> float:
return 21.456
def first_reading(source: Source[float]) -> float:
return source.read()
print(report([1.25, 3.5], fixed)) # Output: ['1.2', '3.5']
print(fixed(first_reading(Sensor()))) # Output: 21.46
A function such as fixed satisfies Formatter because its signature, including the keyword-only digits, matches the declared __call__; a function without that keyword would be rejected by a type checker, although nothing fails at run time until the call. The class Sensor satisfies Source[float] structurally, and the type parameter lets the checker know that first_reading returns a float. Python 3.13 added typing.get_protocol_members and typing.is_protocol, which let code inspect a protocol's members instead of reading private attributes.
Fog of War: What runtime_checkable Can See
A protocol decorated with runtime_checkable can be used with isinstance, but the check only verifies that the members exist, never their signatures, a limitation already shown in the article devoted to advanced type hints. Since Python 3.12, the check looks the members up with inspect.getattr_static, so attributes produced dynamically are invisible to it, and protocols that contain data members cannot be used with issubclass at all.
import timeit
from typing import Protocol, runtime_checkable
@runtime_checkable
class Closeable(Protocol):
def close(self) -> None: ...
@runtime_checkable
class Named(Protocol):
name: str
class File:
name = "log.txt"
def close(self) -> None:
pass
class Proxy:
def __init__(self, target):
self._target = target
def __getattr__(self, attr):
return getattr(self._target, attr)
wrapped = Proxy(File())
print(isinstance(wrapped, Closeable), hasattr(wrapped, "close")) # Output: False True
try:
issubclass(File, Named)
except TypeError as error:
print(error) # Output: Protocols with non-method members don't support issubclass()
f = File()
slow = timeit.timeit(lambda: isinstance(f, Closeable), number=100_000)
fast = timeit.timeit(lambda: hasattr(f, "close"), number=100_000)
print(slow > 2 * fast) # Output: True
The proxy forwards close through __getattr__, the technique described in the article devoted to proxy objects, so hasattr finds the method while the protocol check does not, because the static lookup never calls __getattr__. On CPython 3.12, the isinstance check took about 190 nanoseconds against about 44 for hasattr, which is why the documentation recommends hasattr in performance-sensitive code.
Pitfalls of Protocols
A protocol is a promise checked by tools rather than by the interpreter, so most errors come from expecting run-time enforcement or from members that the checker cannot see. Six pitfalls are distinguished, which are the following:
- No run-time enforcement. Without a type checker, a class with a wrong signature is accepted silently and fails only when the method is called.
isinstancechecks names only. A runtime-checkable protocol accepts any object with members of the right names, whatever their signatures.- Dynamic attributes are invisible. Since Python 3.12, members provided by
__getattr__do not satisfy a runtime check. issubclasswith data members. Protocols that declare variables raiseTypeErrorinissubclass.- Defaults without subclassing. Default methods of a protocol reach only classes that subclass it explicitly.
- Undeclared attributes. Attributes assigned only inside methods are not protocol members, so the protocol must declare them in its body.
The second, third and fourth pitfalls are reproduced in the example of the previous section, and the fifth in the first example, where only the explicit subclass receives the method greet.
Choosing an Interface Mechanism
Consequently, a protocol suits interfaces checked before the program runs and satisfied by classes that the author does not control, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| Accepting any object with given methods, checked statically | typing.Protocol |
| Classes that the author does not control | typing.Protocol |
| A family that shares code and must be checked at instantiation | abc.ABC with abstractmethod |
| Default methods for implementers | Explicit subclassing of the protocol, or an ABC |
| A callable with keyword arguments or defaults | A callback protocol with __call__ |
| A quick run-time check in a hot path | hasattr or callable |
| Checking signatures, not only names | A static type checker |
Conclusion
It is concluded that typing.Protocol brings duck typing into static checking, that its members include methods, annotated variables and properties, and that callback and generic protocols describe callables and containers that Callable and concrete classes cannot. This magic belongs to the type checker: at run time a protocol is checked only on request, only by names, without dynamic attributes since Python 3.12, and at a measurable cost. Objects that can be awaited, from coroutines to tasks and custom classes with __await__, are the subject of a future article of this series.