CKTIS / Python
typing.runtime_checkable
Enable an isinstance test for a protocol using the presence of members.
Version: Python 3.14; repository image, production runtime not attested
Syntax
@runtime_checkable
class Reader(Protocol): ...Enable an isinstance test for a protocol using the presence of members.
The runtime test does not validate method signatures or annotated types. Since Python 3.12 it uses static attribute lookup and freezes the required members when the protocol class is created. A method with the wrong arity can pass the test and fail when called.
A data protocol with non-method members supports isinstance, but issubclass with that protocol raises TypeError.
Examples
from typing import Protocol, runtime_checkable
@runtime_checkable
class Reader(Protocol):
def read(self) -> str: ...
class Wrong:
def read(self, size):
return size
candidate = Wrong()
print(isinstance(candidate, Reader))
try:
candidate.read()
except TypeError:
print("incompatible signature")
@runtime_checkable
class Tagged(Protocol):
tag: str
class Record:
tag = "shown"
assert isinstance(Record(), Tagged)
try:
issubclass(Record, Tagged)
except TypeError:
print("instance check only")
else:
raise AssertionError("unexpected subclass check")
Result
True incompatible signature instance check only
A data protocol with non-method members supports isinstance, but issubclass with that protocol raises TypeError.