Created
June 2, 2016 14:07
-
-
Save methane/d18c66d38b1916e7c36883c0a83f0a01 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
from typing import Generic, TypeVar, Optional | |
class BaseModel: | |
pass | |
M = TypeVar('M', bound=BaseModel) | |
class BaseRepository(Generic[M]): | |
model_class = None #type: type | |
@classmethod | |
def get(cls, pk: int) -> M: | |
"""Find by PK""" | |
... | |
class MyModel(BaseModel): | |
pk = None #type: int | |
name = None #type: str | |
def __init__(self, name: str) -> None: | |
self.name = name | |
class MyModelRepository(BaseRepository[MyModel]): | |
model_class = MyModel | |
@classmethod | |
def find_by_name(cls, name: str) -> Optional[MyMydel]: | |
... | |
def main() -> None: | |
ins = MyModelRepository.get(42) | |
print(ins.pk) | |
# assert isinstance(ins, MyModel) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Funny, you left out one important piece: find_by_name references cls.model_class. Anyway, I got the use case.