3 ms·
Pydantic does though. class A(BaseModel): status: Literal["success"] class B(BaseModel): status: Literal["error"] class C(BaseModel,
by Spivak 3y ago
Pydantic does though.
class A(BaseModel):
status: Literal["success"]
class B(BaseModel):
status: Literal["error"]
class C(BaseModel, ABC):
__root__: Union[A, B] = Field(discriminator="status")
aorb = C.parse_obj(blah…).__root__
if aorb.status == "error":
# aorb will type check as B.
- b33j0r 3y agoYou are a friend and a scholar. I was looking for a solution in pydantic that is wildly relevant. Thanks, I didn’t realize that was implemented/existed. My only objection is using ABC in your MRO. Haha, just a little bit overloaded with abstract base classes and using A, B, and C. I got it eventually! Cool.
- Spivak 3y agoYa know what, on reading that that does seem confusing. My brain had long since internalized ABC as a single token I didn't even notice.
- LoganDark 3y agoI believe this is a good example of type narrowing :)