CKTIS / Python
typing.Protocol
Opisuje štrukturálne rozhranie pre statickú kontrolu.
Verzia: Python 3.14; repository image, production runtime not attested
Syntax
class SizedLabel(Protocol): ...Opisuje štrukturálne rozhranie pre statickú kontrolu.
Trieda so zodpovedajúcimi členmi ho splní bez výslovnej dedičnosti.
Príklad zavolá potrebnú metódu, ale isinstance s protokolom bez runtime_checkable vyvolá TypeError.
Príklady
from typing import Protocol
class Labelled(Protocol):
def label(self) -> str: ...
class Item:
def label(self) -> str:
return "item"
def show(x: Labelled) -> str:
return x.label()
print(show(Item()))
try:
isinstance(Item(), Labelled)
except TypeError:
print("static protocol")
Výsledok
item static protocol
Príklad zavolá potrebnú metódu, ale isinstance s protokolom bez runtime_checkable vyvolá TypeError.