typing.Protocol — class Protocol(Generic)
| Use Case | Command / Code | Description |
|---|---|---|
| 🏗️ Define a protocol | class Proto(Protocol): | Base class for protocol classes. |
| 🦆 Structural subtyping | class C: def meth(self) -> int: ... | Static duck-typing recognized by type checkers. |
| ✅ Runtime checkable | @typing.runtime_checkable | Simple-minded runtime protocol checking attribute presence. |
| 🧬 Generic protocol | class GenProto(Protocol[T]): | Protocols can be generic over types. |
Base class for protocol classes.
Protocol classes are defined as:
class Proto(Protocol):
def meth(self) -> int:
...
Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing), for example:
class C:
def meth(self) -> int:
return 0
def func(x: Proto) -> int:
return x.meth()
func(C()) # Passes static type check
See PEP 544 for details. Protocol classes decorated with @typing.runtime_checkable act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures. Protocol classes can be generic, they are defined as:
class GenProto(Protocol[T]):
def meth(self) -> T:
...
ProtocolGenericbuiltins.object__init_subclass__(*args, **kwargs) from typing._ProtocolMeta
__abstractmethods__ = frozenset()__parameters__ = ()__class_getitem__(params) from typing._ProtocolMetaGenerated by phpman v4.10.0-7-g98e9fd5 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-09-02 19:13 @216.73.216.239
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)