New submission from Joseph Perez <jope...@hotmail.fr>:

`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?

----------
messages: 403554
nosy: joperez
priority: normal
severity: normal
status: open
title: types.UnionType is not subscriptable
versions: Python 3.10

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue45418>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to