CKTIS / Python
Anotacije tipova i protokoli
Anotacija može opisati sučelje za statičku provjeru bez zahtjeva za zajedničkom osnovnom klasom.
Verzija: Python 3.14; repository image, production runtime not attested
Sintaksa
class Reader(Protocol):
def read(self) -> str: ...Anotacija može opisati sučelje za statičku provjeru bez zahtjeva za zajedničkom osnovnom klasom.
Protocol strukturno opisuje metode i njihove potpise. Poziv funkcije ne provodi anotacije. runtime_checkable omogućuje da isinstance provjeri prisutnost članova bez provjere parametara ili povratnog tipa.
Message daje READY. NeedsKey ima read i prolazi provjeru iako poziv bez argumenta izaziva TypeError.
from typing import Protocol,runtime_checkable,get_type_hints
@runtime_checkable
class Reader(Protocol):
def read(self)->str: ...
class Bad:
def read(self, extra): return extra
def display(source:Reader): return source.read()
assert get_type_hints(display)['source'] is Reader
assert isinstance(Bad(),Reader)
try: display(Bad())
except TypeError: pass
else: raise AssertionError
Primjeri
from typing import Protocol, runtime_checkable
@runtime_checkable
class Reader(Protocol):
def read(self) -> str: ...
class Message:
def read(self) -> str:
return "ready"
class NeedsKey:
def read(self, key):
return key
def display(source: Reader):
return source.read().upper()
print(display(Message()), isinstance(NeedsKey(), Reader))
Rezultat
READY True
Message daje READY. NeedsKey ima read i prolazi provjeru iako poziv bez argumenta izaziva TypeError.