Simple user-defined protocols

You can define your own protocol class by inheriting the special Protocolclass:

  1. from typing import Iterable
  2. from typing_extensions import Protocol
  3.  
  4. class SupportsClose(Protocol):
  5. def close(self) -> None:
  6. ... # Empty method body (explicit '...')
  7.  
  8. class Resource: # No SupportsClose base class!
  9. # ... some methods ...
  10.  
  11. def close(self) -> None:
  12. self.resource.release()
  13.  
  14. def close_all(items: Iterable[SupportsClose]) -> None:
  15. for item in items:
  16. item.close()
  17.  
  18. close_all([Resource(), open('some/file')]) # Okay!

Resource is a subtype of the SupportsClose protocol since it definesa compatible close method. Regular file objects returned by open() aresimilarly compatible with the protocol, as they support close().

Note

The Protocol base class is provided in the typing_extensionspackage for Python 2.7 and 3.4-3.7. Starting with Python 3.8, Protocolis included in the typing module.