WissensdatenbankPrüfungszentrum
DEDeutsch
Sprache wählen13

CKTIS / Python

typing.runtime_checkable

Erlaubt isinstance anhand vorhandener Protokollmitglieder ohne Prüfung ihrer Typen oder Signaturen.

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

Syntax

@runtime_checkable
class Reader(Protocol): ...

Erlaubt isinstance anhand vorhandener Protokollmitglieder ohne Prüfung ihrer Typen oder Signaturen.

Seit Python 3.12 erfolgt die Attributsuche statisch und die geforderten Mitglieder stehen bei Erzeugung des Protokolls fest. Eine Methode mit falscher Parameterzahl besteht den Test, ihr Aufruf scheitert.

Ein Datenprotokoll mit einem Nichtmethodenattribut erlaubt isinstance, bei issubclass löst es dagegen TypeError aus.

Beispiele

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

Ergebnis

True
incompatible signature
instance check only

Ein Datenprotokoll mit einem Nichtmethodenattribut erlaubt isinstance, bei issubclass löst es dagegen TypeError aus.

Quellen