CKTIS / Python
typing.runtime_checkable
Pozwala użyć isinstance do sprawdzenia obecności składowych protokołu, bez kontroli ich typów i sygnatur.
Wersja: Python 3.14; repository image, production runtime not attested
Składnia
@runtime_checkable
class Reader(Protocol): ...Pozwala użyć isinstance do sprawdzenia obecności składowych protokołu, bez kontroli ich typów i sygnatur.
Od Pythona 3.12 wyszukiwanie atrybutów jest statyczne, a zbiór wymaganych składowych ustala się przy tworzeniu protokołu. Metoda o złej liczbie parametrów przechodzi test, ale jej wywołanie zawodzi.
Protokół z atrybutem danych obsługuje isinstance, lecz użycie go w issubclass zgłasza TypeError.
Przykłady
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")
Wynik
True incompatible signature instance check only
Protokół z atrybutem danych obsługuje isinstance, lecz użycie go w issubclass zgłasza TypeError.