a way to instantiate models where you don't know which model in a union needs to be instantiated #4140
DetachHead
started this conversation in
Feature Request
Replies: 1 comment 2 replies
-
Hi @DetachHead, You can define your own let's call it from typing import Union, Literal, Any
from pydantic import BaseModel
from pydantic.dataclasses import dataclass
@dataclass
class SuccessResponse:
success: Literal[True]
@dataclass
class FailedResponse:
success: Literal[False]
failed_reason: str
class SmartUnion:
def __class_getitem__(cls, item):
class _Model(BaseModel):
__root__: Union[item]
class Config:
smart_union = True
def _parse(**kwargs: Any) -> Any:
return _Model(__root__=kwargs).__root__
return _parse
Response = SmartUnion[SuccessResponse, FailedResponse]
print(Response(**{"success": True}))
print(Response(**{"success": False, "failed_reason": "failed"})) SuccessResponse(success=True)
FailedResponse(success=False, failed_reason='failed') Or if you don't need from typing import Literal, Union
from pydantic import parse_obj_as
from pydantic.dataclasses import dataclass
@dataclass
class SuccessResponse:
success: Literal[True]
@dataclass
class FailedResponse:
success: Literal[False]
failed_reason: str
class SmartUnion:
def __class_getitem__(cls, item):
return lambda **kwargs: parse_obj_as(Union[item], kwargs)
Response = SmartUnion[SuccessResponse, FailedResponse]
print(Response(**{"success": True}))
print(Response(**{"success": False, "failed_reason": "failed"})) |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
something like
here,
pydantic.Union.__class_getitem__
could return a constructor that iterates over all the classes in the union and attempts to instantiate them all until one of them succeedsBeta Was this translation helpful? Give feedback.
All reactions