Skip to content

False-positive errors when using type[T] (or Type[T]) in a PEP 604 type alias #12392

Description

@AlexWaygood

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:

fromtypingimportType, TypeAliasA=type[int] |str# error: Value of type "Type[type]" is not indexableB=Type[int] |str# error: Unsupported left operand type for | ("object")C: TypeAlias=type[int] |str# error: Value of type "Type[type]" is not indexableD: 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 indexableF: 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:

fromtypingimportUnionG=Union[type[int], str]

To Reproduce

Mypy playground link here.

Expected Behavior

No error should be reported.

Cc. @JelleZijlstra

Metadata

Metadata

Assignees

No one assigned

    Labels

    affects-typeshedAnything that blocks a typeshed changebugmypy got something wrongfalse-positivemypy gave an error on correct codetopic-pep-604PEP 604 (union | operator)topic-type-aliasTypeAlias and other type alias issues

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions