I have a base Python (3.8) abstract base class, with two classes inheriting from it:
BoundedModel = TypeVar("BoundedModel", bound=CustomBaseModel)
class BaseDataStore(ABC, Generic[BoundedModel]):
def __init__(self, resource_name: str) -> None:
self.client = client(resource_name)
@abstractmethod
def get_all(self) -> List[BoundedModel]:
pass
class MetadataStore(BaseDataStore[Metadata]):
def get_all(self) -> List[Metadata]:
items = self.client.get_all()
return [Metadata(**item) for item in items]
class TranscriptStore(BaseDataStore[Transcript]):
def get_all(self) -> List[Transcript]:
items = self.client.get_all()
return [Transcript(**item) for item in items]
The CustomBaseModel
bound for BoundedModel
represents a pydantic class, meaning
that Metadata
and Transcript
are pydantic class models used for validation.
The concrete implementations of get_all
all do the exact same thing:
they validate the data with the Pydantic bounded model. This works, but forces me
to spell out the concrete implementation for each BaseDataStore
child.
Is there any way that I could implement get_all
as a generic method (rather than abstract) in the parent BaseDataStore
, therefore removing the need for concrete implementations in the children?