Base de conocimientosCentro de exámenes
ESEspañol
Elegir idioma13

CKTIS / Python

typing.Protocol

Describe una interfaz estructural para la comprobación estática.

Versión: Python 3.14; repository image, production runtime not attested

Sintaxis

class SizedLabel(Protocol): ...

Describe una interfaz estructural para la comprobación estática.

Una clase con miembros compatibles la satisface sin herencia explícita.

El ejemplo llama al método requerido pero isinstance con un protocolo sin runtime_checkable provoca TypeError.

Ejemplos

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

Resultado

item
static protocol

El ejemplo llama al método requerido pero isinstance con un protocolo sin runtime_checkable provoca TypeError.

Fuentes