Created
August 9, 2020 11:56
-
-
Save jaycosaur/2170c246d81ce11af64b59dbc34d9371 to your computer and use it in GitHub Desktop.
Interfaces [python-ABC] - 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 abc import ABC, abstractmethod | |
class FileHandlerABC(ABC): | |
@abstractmethod | |
def open(self) -> bytes: | |
... | |
@abstractmethod | |
def close(self) -> None: | |
... | |
# with usage like: | |
def get_contents(file_handler: FileHandlerABC) -> bytes: | |
assert isinstance(file_handler, FileHandlerABC) | |
try: | |
return file_handler.open() | |
finally: | |
file_handler.close() | |
# note this must extend the abstract base class | |
class MyFile(FileHandlerABC): | |
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