CKTIS / Python
typing.Protocol
Opisuje strukturalny interfejs dla analizy statycznej.
Wersja: Python 3.14; repository image, production runtime not attested
Składnia
class SizedLabel(Protocol): ...Opisuje strukturalny interfejs dla analizy statycznej.
Klasa o zgodnych składowych spełnia go bez jawnego dziedziczenia.
Przykład wywołuje wymaganą metodę, lecz isinstance z protokołem bez runtime_checkable zgłasza TypeError.
Przykłady
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")
Wynik
item static protocol
Przykład wywołuje wymaganą metodę, lecz isinstance z protokołem bez runtime_checkable zgłasza TypeError.