CKTIS / Python
typing.runtime_checkable
Umožňuje isinstance ověřit přítomnost členů protokolu bez kontroly typů a signatur.
Verze: Python 3.14; repository image, production runtime not attested
Syntaxe
@runtime_checkable
class Reader(Protocol): ...Umožňuje isinstance ověřit přítomnost členů protokolu bez kontroly typů a signatur.
Od Pythonu 3.12 je vyhledávání atributů statické a požadované členy se stanoví při vytvoření protokolu. Metoda s nesprávným počtem parametrů testem projde, ale volání selže.
Protokol s datovým atributem podporuje isinstance, ale použití v issubclass vyvolá TypeError.
Příklady
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")
Výsledek
True incompatible signature instance check only
Protokol s datovým atributem podporuje isinstance, ale použití v issubclass vyvolá TypeError.