Description
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
Activity
type[T]
(orType[T]
) in a PEP 604 type alias #12392gvanrossum commentedon Jul 14, 2022
I hit this with
T = Callable[[], int] | None
. No PEP 604TypeAlias
needed in this repro.AlexWaygood commentedon Jul 14, 2022
That is a PEP 604 type alias, and it's the same as my first example :-)
If you were to write that type alias without PEP 604, it would be
T = Union[Callable[[], int], None]
orT = Optional[Callable[[], int]]
gvanrossum commentedon Jul 14, 2022
flake8-pyi
inpre-commit
checks typeddjango/django-stubs#1253ilevkivskyi commentedon Nov 21, 2022
The original example works correctly on master (assuming you use 3.10+).
9 remaining items