Created
March 30, 2024 22:27
-
-
Save normanlmfung/a2a216853e1db89ce966451059dd7f8c to your computer and use it in GitHub Desktop.
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
# Taken DIRECTLY from William's article https://realpython.com/python-interface/ | |
import abc | |
class FormalParserInterface(metaclass=abc.ABCMeta): | |
@classmethod | |
def __subclasshook__(cls, subclass): | |
print("FormalParserInterface.__subclasshook__") | |
return (hasattr(subclass, 'load_data_source') and | |
callable(subclass.load_data_source) and | |
hasattr(subclass, 'extract_text') and | |
callable(subclass.extract_text)) | |
class CsvParserNew: | |
def load_data_src(self, path: str, file_name: str) -> str: | |
print("CsvParserNew.load_data_source") | |
def extract_text(self, full_file_path: str) -> dict: | |
print("CsvParserNew.extract_text") | |
class PdfParserNew(FormalParserInterface): | |
def load_data_source(self, path: str, file_name: str) -> str: | |
print("PdfParserNew.load_data_source") | |
def extract_text(self, full_file_path: str) -> dict: | |
print("PdfParserNew.extract_text") | |
@FormalParserInterface.register # This will trigger FormalParserInterface.__subclasshook__ when you declare the class (i.e. BEFORE you even instantiate it) | |
class EmlParserNew(FormalParserInterface): | |
def load_data_source(self, path: str, file_name: str) -> str: | |
print("EmlParserNew.load_data_source") | |
def extract_text(self, full_file_path: str) -> dict: | |
print("EmlParserNew.extract_text") | |
pdf = PdfParserNew() | |
eml = EmlParserNew() | |
print(issubclass(CsvParserNew, FormalParserInterface)) # False. issubclass will trigger FormalParserInterface.__subclasshook__ | |
print(issubclass(PdfParserNew, FormalParserInterface)) # True. | |
print(issubclass(EmlParserNew, FormalParserInterface)) # True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment