CKTIS / Python
typing.runtime_checkable
Umožňuje isinstance overiť prítomnosť členov protokolu bez kontroly typov a signatúr.
Verzia: Python 3.14; repository image, production runtime not attested
Syntax
@runtime_checkable
class Reader(Protocol): ...Umožňuje isinstance overiť prítomnosť členov protokolu bez kontroly typov a signatúr.
Od Pythonu 3.12 je vyhľadávanie atribútov statické a požadované členy sa určia pri vytvorení protokolu. Metóda s nesprávnym počtom parametrov testom prejde, ale volanie zlyhá.
Protokol s dátovým atribútom podporuje isinstance, ale použitie v issubclass vyvolá TypeError.
Prí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ýsledok
True incompatible signature instance check only
Protokol s dátovým atribútom podporuje isinstance, ale použitie v issubclass vyvolá TypeError.