Simple user-defined protocols
You can define your own protocol class by inheriting the special Protocol
class:
- from typing import Iterable
- from typing_extensions import Protocol
- class SupportsClose(Protocol):
- def close(self) -> None:
- ... # Empty method body (explicit '...')
- class Resource: # No SupportsClose base class!
- # ... some methods ...
- def close(self) -> None:
- self.resource.release()
- def close_all(items: Iterable[SupportsClose]) -> None:
- for item in items:
- item.close()
- 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_extensions
package for Python 2.7 and 3.4-3.7. Starting with Python 3.8, Protocol
is included in the typing
module.