[issue45418] types.UnionType is not subscriptable
Ken Jin
report at bugs.python.org
Sun Oct 10 01:59:28 EDT 2021
Ken Jin <kenjin4096 at gmail.com> added the comment:
I don't understand your example, T | None doesn't return a types.Union object, it returns typing.Union/typing.Optional. (I'm assuming this T is the TypeVar in typing). Which *is* subscriptable.
>>> (T | None)[int].__origin__
typing.Union
If you meant to say: why is typing.Union[] allowed, but not types.UnionType[]? That is intentional. types.UnionType is only meant for builtin types. Once you union with *any* type from typing, it will convert to a typing.Union.
>>> type(int | str)
<class 'types.UnionType'>
>>> int | str | T
typing.Union[int, str, ~T]
If you intend to reconstruct a types.Union from another types.Union, you can do:
args = get_args(int | str)
import operator, functools
functools.reduce(operator.or_, args)
And guard this code with an isinstance(tp, types.UnionType) check.
----------
nosy: +gvanrossum, kj, serhiy.storchaka
status: open -> pending
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45418>
_______________________________________
More information about the Python-bugs-list
mailing list