Created
August 9, 2020 11:57
-
-
Save jaycosaur/8c39f64fbb732c86031f8851a8401af4 to your computer and use it in GitHub Desktop.
Interfaces [python-protocol] - Typescript to Python field guide
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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