Re:Proposing a Struct Syntax for Python
by fritzo on Wednesday June 14, 2023 @02:12PM
(#36330091)
Do you mean Python's lack of a labeled union type?
[ Parent
| on HN ]
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.You 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.
Ya 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.
Re:Proposing a Struct Syntax for Python
by LoganDark on Wednesday June 14, 2023 @04:32PM
(#36332177)
I believe this is a good example of type narrowing :)
Re:Proposing a Struct Syntax for Python
by LoganDark on Wednesday June 14, 2023 @04:31PM
(#36332170)
Yeah. Been spoiled by Rust.
Re:Proposing a Struct Syntax for Python
by contravariant on Wednesday June 14, 2023 @04:49PM
(#36332435)
It doesn't seem that far off though, it does have a union type and with pattern matching you can achieve pretty much the same thing (sure you may need a few extra classes if the types aren't distinct already but that seems like a small difference).
I don't know if type checkers can figure out if a pattern match statement is exhaustive yet though, that would be interesting.