Skip to content

Instantly share code, notes, and snippets.

@jaycosaur
Created August 9, 2020 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaycosaur/8c39f64fbb732c86031f8851a8401af4 to your computer and use it in GitHub Desktop.
Save jaycosaur/8c39f64fbb732c86031f8851a8401af4 to your computer and use it in GitHub Desktop.
Interfaces [python-protocol] - Typescript to Python field guide
from typing import Protocol, runtime_checkable
@runtime_checkable
class FileHandlerProtocol(Protocol):
def open(self) -> bytes:
...
def close(self) -> None:
...
# with usage like:
def get_contents(file_handler: FileHandlerProtocol) -> bytes:
assert isinstance(file_handler, FileHandlerProtocol)
try:
return file_handler.open()
finally:
file_handler.close()
# implicitly implements the FileHandlerProtocol interface
class MyFile:
def open(self) -> bytes:
return b"hello"
def close(self) -> None:
return
contents = get_contents(MyFile()) # b"hello"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment