Using isinstance() with protocols
You can use a protocol class with isinstance()
if you decorate itwith the @runtime_checkable
class decorator. The decorator addssupport for basic runtime structural checks:
- from typing_extensions import Protocol, runtime_checkable
- @runtime_checkable
- class Portable(Protocol):
- handles: int
- class Mug:
- def __init__(self) -> None:
- self.handles = 1
- mug = Mug()
- if isinstance(mug, Portable):
- use(mug.handles) # Works statically and at runtime
isinstance()
also works with the predefined protocolsin typing
such as Iterable
.
Note
isinstance()
with protocols is not completely safe at runtime.For example, signatures of methods are not checked. The runtimeimplementation only checks that all protocol members are defined.