Skip to content

Instantly share code, notes, and snippets.

@Fkawala
Created May 27, 2021 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fkawala/00a5b79d80b3dbe8e4e6254ae5638a4d to your computer and use it in GitHub Desktop.
Save Fkawala/00a5b79d80b3dbe8e4e6254ae5638a4d to your computer and use it in GitHub Desktop.
from typing import ClassVar, Type, Dict, Generic, TypeVar, Any, List
from pydantic import BaseModel
#
T = TypeVar('T', bound=BaseModel)
class Response(BaseModel, Generic[T]):
data: Type[BaseModel]
metadata: Dict[str, Any]
def __init__(self, *a, **kw) -> None:
_metadata = kw.pop("metadata", {})
_data = type(Type[T])(*a, **kw)
super().__init__(data=_data, metadata=_metadata)
class X(BaseModel):
"""
This class is the model used to answer to the client on the /parse route.
"""
successes: List[str]
failures: List[int]
class MyResponse(Response[X]):
data: X
print(MyResponse(successes=["1","qsd"], failures=[3,4,5], metadata={"zzz": 133}).dict())
@Fkawala
Copy link
Author

Fkawala commented May 31, 2021

class Response(BaseModel):
    data: Type[BaseModel]
    metadata: Dict[str, Any]

    def __init__(self, *a, **kw) -> None:
        _metadata = kw.pop("metadata", {})
        _data_cls = self.__annotations__["data"]
        _data = _data_cls(*a, **kw)
        super().__init__(data=_data, metadata=_metadata)

class X(BaseModel):
    """
    This class is the model used to answer to the client on the /parse route.
    """
    successes: List[str]
    failures: List[int]

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