Skip to content

Instantly share code, notes, and snippets.

@methane
Created June 2, 2016 14:07
Show Gist options
  • Save methane/d18c66d38b1916e7c36883c0a83f0a01 to your computer and use it in GitHub Desktop.
Save methane/d18c66d38b1916e7c36883c0a83f0a01 to your computer and use it in GitHub Desktop.
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()
@gvanrossum
Copy link

Funny, you left out one important piece: find_by_name references cls.model_class. Anyway, I got the use case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment