Base de connaissancesCentre d’examen
FRFrançais
Choisir la langue13

CKTIS / Python

typing.Protocol

Décrit une interface structurelle pour l’analyse statique.

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

Syntaxe

class SizedLabel(Protocol): ...

Décrit une interface structurelle pour l’analyse statique.

Une classe aux membres compatibles la satisfait sans héritage explicite.

L’exemple appelle la méthode requise mais isinstance avec un protocole sans runtime_checkable lève TypeError.

Exemples

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

Résultat

item
static protocol

L’exemple appelle la méthode requise mais isinstance avec un protocole sans runtime_checkable lève TypeError.

Sources