Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / Python

Adnotacje typów i protokoły

Adnotacja może opisać wymagany interfejs dla analizatora statycznego bez narzucania wspólnej klasy bazowej.

Wersja: Python 3.14; repository image, production runtime not attested

Składnia

class Reader(Protocol):
    def read(self) -> str: ...

Adnotacja może opisać wymagany interfejs dla analizatora statycznego bez narzucania wspólnej klasy bazowej.

Protocol opisuje metody i ich sygnatury strukturalnie. Wywołanie funkcji nie wymusza adnotacji. runtime_checkable dopuszcza isinstance sprawdzające obecność członków, lecz nie zgodność parametrów i wyniku.

Message daje READY. NeedsKey przechodzi sprawdzenie obecności read, choć wywołanie bez argumentu zgłasza 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

Przykłady

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))

Wynik

READY True

Message daje READY. NeedsKey przechodzi sprawdzenie obecności read, choć wywołanie bez argumentu zgłasza TypeError.

Źródła