Replies: 1 comment 2 replies
-
Order appears to be preserved in practice in 3.13 and 3.14. I don't recall whether we changed that recently, but I'd be open to changing the docs to make that guarantee for |
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
Uh oh!
There was an error while loading. Please reload this page.
-
I would like to use type annotations (especially
Annotated
) to add information to class members for some parsing code to use at runtime (viaget_type_hints
).When some element can have multiple types, they must usually be tried in a specific order; if the order is unstable, the parser becomes non-deterministic.
Unfortunately, the
typing
docs state thatget_args
does not necessarily preserve order ofUnion
members, due to type caching[1].As a concrete example, I have a field annotated
MyIntEnum | int
, for which the parser reads a number from its input stream, and then return an instance ofMyIntEnum
if possible, or just a plainint
if not.If this union gets re-ordered with
int
first, the parser will never even try to return an instance ofMyIntEnum
.I can understand that caching is very important for type checking, which is a much more important use case for type annotations than mine, so I'm thinking more in the direction of working around this limitation somehow.
I could easily implement some kind of
OrderedUnion[...]
that would work for my parser, but I don't see how it would be possible to get a type checker to interpret such a thing correctly -- and I would lose the|
syntax sugar.I'm assuming it's not possible to monkey patch
Union
, as I remember from my last trip through cpython thatUnion
is implemented pretty low-level.Does the "Type School" have any ideas or advice?
Beta Was this translation helpful? Give feedback.
All reactions