KennisbankExamencentrum
NL · NLNederlands (Nederland)
Taal kiezen13

CKTIS / Python

typing.Protocol

Beschrijft een structurele interface voor statische controle.

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

Syntax

class SizedLabel(Protocol): ...

Beschrijft een structurele interface voor statische controle.

Een klasse met passende leden voldoet zonder expliciete overerving.

Het voorbeeld roept de vereiste methode aan maar isinstance met een protocol zonder runtime_checkable geeft TypeError.

Voorbeelden

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

Resultaat

item
static protocol

Het voorbeeld roept de vereiste methode aan maar isinstance met een protocol zonder runtime_checkable geeft TypeError.

Bronnen