WissensdatenbankPrüfungszentrum
DEDeutsch
Sprache wählen13

CKTIS / Python

typing.Protocol

Beschreibt eine strukturelle Schnittstelle für die statische Prüfung.

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

Syntax

class SizedLabel(Protocol): ...

Beschreibt eine strukturelle Schnittstelle für die statische Prüfung.

Eine Klasse mit passenden Mitgliedern erfüllt sie ohne ausdrückliche Vererbung.

Der Aufruf der geforderten Methode gelingt, aber isinstance mit dem Protokoll ohne runtime_checkable löst TypeError aus.

Beispiele

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

Ergebnis

item
static protocol

Der Aufruf der geforderten Methode gelingt, aber isinstance mit dem Protokoll ohne runtime_checkable löst TypeError aus.

Quellen