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:

  1. from typing_extensions import Protocol, runtime_checkable
  2.  
  3. @runtime_checkable
  4. class Portable(Protocol):
  5. handles: int
  6.  
  7. class Mug:
  8. def __init__(self) -> None:
  9. self.handles = 1
  10.  
  11. mug = Mug()
  12. if isinstance(mug, Portable):
  13. 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.