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