python/응용
pydantic: Generics
wefree
2023. 5. 28. 22:29
https://mypy.readthedocs.io/en/stable/generics.html
https://docs.pydantic.dev/latest/usage/models/#generic-models
from typing import TypeVar, List, Generic
from pydantic import BaseModel
from pydantic.generics import GenericModel
T = TypeVar('T', bound=BaseModel, covariant=True)
class Dog(BaseModel):
name: str
age: int
class Paging(GenericModel, Generic[T]):
total: int
page: int
size: int
items: List[T]
dog1 = Dog(name="A", age=10)
dog2 = Dog(name="B", age=20)
dog_paging: Paging[Dog] = Paging[Dog](total=10, page=1, size=5, items=[dog1, dog2])
print(dog_paging.json())