Skip to content

False-positive error when using Callable in a PEP 604 type alias #12393

Closed
@AlexWaygood

Description

@AlexWaygood

Bug Report

The following snippet works fine at runtime on 3.10+. It should be accepted as a valid type alias definition on Python 3.10+ (and should be accepted in stub files regardless of Python version). However, mypy raises a false-positive error. The error does not go away if you use typing.TypeAlias:

from typing import Callable, TypeAlias

A = Callable[[], str] | int  # error: Unsupported left operand type for | ("object")
B: TypeAlias = Callable[[], str] | int  # error: Unsupported left operand type for | ("object")

Mypy does accept the following (with the order of types reversed) as a valid type alias on Python 3.10+ and in stub files:

C = int | Callable[[], str]  # No error using Python 3.10 (in a `.py file), or in a stub file on any Python version.

Much like with #12392, this error is only reproduceable if Callable is the outermost type. The following produces no errors:

D = list[Callable[[], str] | int]

There is also an additional bug that only exists for stub files running with --python-version set to 3.9 or lower, when using a Callable that has a PEP 604 union as its return type or a PEP 604 union in its parameter specification, and when the Callable is itself in a PEP 604 union:

X = int | Callable[[], str | bool]  # error: Unsupported left operand type for | ("Type[str]")
Y = int | Callable[[str | bool], str]  # error: Unsupported left operand type for | ("Type[str]")

To Reproduce

  • Mypy playground link here for the errors which affect stubs and .py files.
  • For the stub-specific errors, paste the code samples into a .pyi file, then run mypy on the file with --python-version=3.9.

Expected Behavior

No errors 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