Skip to content

Instantly share code, notes, and snippets.

@jaycosaur
Created August 9, 2020 11:56
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/2170c246d81ce11af64b59dbc34d9371 to your computer and use it in GitHub Desktop.
Save jaycosaur/2170c246d81ce11af64b59dbc34d9371 to your computer and use it in GitHub Desktop.
Interfaces [python-ABC] - Typescript to Python field guide
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