Description
Bug Report
The following two snippets (one using builtins.type
, the other using typing.Type
) both work fine at runtime on 3.10+. They should be accepted as valid type alias definitions on Python 3.10+ (and should be accepted in stub files regardless of Python version). However, mypy raises false-positive errors for both. The errors do not go away if you use typing.TypeAlias
:
from typing import Type, TypeAlias
A = type[int] | str # error: Value of type "Type[type]" is not indexable
B = Type[int] | str # error: Unsupported left operand type for | ("object")
C: TypeAlias = type[int] | str # error: Value of type "Type[type]" is not indexable
D: TypeAlias = Type[int] | str # error: Unsupported left operand type for | ("object")
The order of the types in the union makes no difference when using type[T]
: the following two variants still produce errors:
E = str | type[int] # error: Value of type "Type[type]" is not indexable
F: TypeAlias = str | type[int] # error: Value of type "Type[type]" is not indexable
However, the order of the types in the union does matter if you're using typing.Type[T]
:
B = Type[int] | str # error: Unsupported left operand type for | ("object")
D: TypeAlias = Type[int] | str # error: Unsupported left operand type for | ("object")
G = str | Type[int] # no error
Interestingly, the bug can only be reproduced if type
or Type
is the outermost object in the type alias. Neither of the following two snippets causes mypy errors:
E = list[type[int] | str]
F = type[int | str]
Mypy is also happy with type[T]
or Type[T]
being used in old-style typing.Union
type aliases:
from typing import Union
G = Union[type[int], str]
To Reproduce
Mypy playground link here.
Expected Behavior
No error should be reported.
Cc. @JelleZijlstra
Activity
[-]False-positive errors when using `type[T]` (or Type[T]`) in a PEP 604 type alias[/-][+]False-positive errors when using `type[T]` (or `Type[T]`) in a PEP 604 type alias[/+]Callable
in a PEP 604 type alias #12393wrobell commentedon Apr 12, 2022
I have encountered the following
It looks like the same issue?
AlexWaygood commentedon Apr 12, 2022
@wrobell, I have another issue open for PEP-604 false-positives with respect to
Callable
: #12393. But I agree that these problems are linked.mthuurne commentedon May 31, 2022
This issue seems to exist for any runtime evaluation of
type[X]
, not just in type aliases:This still happens when using the
--python-version 3.10
option.type
class cannot be used as a generic #11424type
with new union syntax inTypeAlias
incorrectly reports 'Value of type "Type[type]" is not indexable' #1297812 remaining items