Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / Python

typing.Protocol

Descreve uma interface estrutural para a análise estática.

Versão: Python 3.14; repository image, production runtime not attested

Sintaxe

class SizedLabel(Protocol): ...

Descreve uma interface estrutural para a análise estática.

Uma classe com membros compatíveis satisfaz a interface sem herança explícita.

O exemplo chama o método exigido mas isinstance com um protocolo sem runtime_checkable lança TypeError.

Exemplos

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

O exemplo chama o método exigido mas isinstance com um protocolo sem runtime_checkable lança TypeError.

Fontes