Description
Feature or enhancement
I'd like some way to runtime inspect a Union and be able to identify that,
A = Union[int, str]
B = Union[A, list[int]]
that A is first argument of B. Today get_args(B) == (int, str, list[int])
and even `B.args == (int, str, list[int])
Pitch
At runtime A is commonly a type alias and may be some long complex type. Being able to extract A back out can be helpful if you have dictionary of types for use cases similar to cattrs that define serializers/deserializers based on types. Or being able to generate documentation that uses A to simplify where it's possible documentation generator registers type aliases and stores some mapping of types -> short names.
How precisely this is done I'm more neutral on. It's fine if eq stays same and collapses them for comparison and get_args should also probably stay same behavior. Could __args__
change to preserve nesting so that B.__args__ == (A, list[int])
while get_args then handles collapsing? Alternative __original_args__
being added could work.
Previous discussion
This is kind of similar to Union ordering runtime question especially in motivation. There is a difference that even today there's already collapsing of Union types being done.
edit: One awkward point I just realized with this is it's unclear to me how nesting would work/mean anything with |
syntax for defining Unions. I'm still mostly using 3.9 (one dependency I want still hasn't released 3.10+ support) so stuck with typing.Union for runtime usages but with | syntax nesting sorta disappears naturally. If this feature only makes sense for typing.Union and most newer usages are expected to move to |
then it may make sense to just accept that distinguishing union alias inside a union is messy.