KennisbankExamencentrum
NL · NLNederlands (Nederland)
Taal kiezen13

CKTIS / Python

typing.runtime_checkable

Laat isinstance de aanwezigheid van protocolleden controleren zonder typen of signaturen te valideren.

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

Syntax

@runtime_checkable
class Reader(Protocol): ...

Laat isinstance de aanwezigheid van protocolleden controleren zonder typen of signaturen te valideren.

Sinds Python 3.12 worden attributen statisch opgezocht en liggen de vereiste leden bij het maken van het protocol vast. Een methode met onjuist aantal parameters doorstaat de test maar de aanroep mislukt.

Een protocol met een gegevensattribuut ondersteunt isinstance maar geeft TypeError bij gebruik in issubclass.

Voorbeelden

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

Resultaat

True
incompatible signature
instance check only

Een protocol met een gegevensattribuut ondersteunt isinstance maar geeft TypeError bij gebruik in issubclass.

Bronnen