On this page
typing.Protocol
Prev: typing.ParamSpecKwargs | Up: typing | Next: typing.SupportsAbs
Rel: typing.AbstractSet, typing.Annotated, typing.Any, typing.assert_never
Ref: docs.python.org — typing.Protocol
Tags: #public #python3 #stdlib #typing
Import
import typing
from typing import Protocol
Signature & Overview
typing.Protocol()
Base class for protocol classes.
Usage
from typing import Protocol, runtime_checkable
@runtime_checkable
class Closable(Protocol):
def close(self) -> None: ...
class Conn:
def close(self) -> None: pass
assert isinstance(Conn(), Closable)
Gotchas
- Structural typing (static duck typing): Classes don't need to inherit from
Closableto satisfy it. @runtime_checkableonly checks attribute existence:isinstance()does not verify method argument or return types at runtime.
REPL Inspect
from typing import Protocol
help(Protocol)
Linked from
Related notes
- tuts/python3/stdlib_module/typing/ParamSpecKwargs Linked here; links to this page; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/SupportsAbs Linked here; links to this page; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/typing/AbstractSet Linked here; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/Annotated Linked here; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/Any Linked here; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/assert_never Linked here; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/assert_type shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/AsyncContextManager shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/AsyncGenerator shared tags: #stdlib, #typing