This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author joperez
Recipients joperez
Date 2021-10-09.21:37:56
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1633815476.2.0.253081799183.issue45418@roundup.psfhosted.org>
In-reply-to
Content
`types.UnionType` is not subscriptable, and this is an issue when type manipulations are done.

A common maniputation I've to do is to substitute all the `TypeVar` of a potential generic type by their specialization in the given context.
For example, given a class:
```python
@dataclass
class Foo(Generic[T]):
    bar: list[T]
    baz: T | None
```
in the case of `Foo[int]`, I want to compute the effective type of the fields, which will be `list[int]` and `int | None`.
It could be done pretty easily by a recursive function:
```python
def substitute(tp, type_vars: dict):
    origin, args = get_origin(tp), get_args(tp)
    if isinstance(tp, TypeVar):
        return type_vars.get(tp, tp)
    elif origin is Annotated:
        return Annotated[(substitute(args[0], type_vars), *args[1:])]
    else:
        return origin[tuple(substitute(arg) for arg in args)]  # this line fails for types.UnionType
```

And this is not the only manipulation I've to do on generic types. In fact, all my library (apischema) is broken in Python 3.10 because of `types.UnionType`.
I've to substitute `types.UnionType` by `typing.Union` everywhere to make things work; `types.UnionType` is just not usable for dynamic manipulations.

I've read PEP 604 and it doesn't mention if `types.UnionType` should be subscriptable or not. Is there a reason for not making it subscriptable?
History
Date User Action Args
2021-10-09 21:37:56joperezsetrecipients: + joperez
2021-10-09 21:37:56joperezsetmessageid: <1633815476.2.0.253081799183.issue45418@roundup.psfhosted.org>
2021-10-09 21:37:56joperezlinkissue45418 messages
2021-10-09 21:37:56joperezcreate