Closed
Labels
Description
Bug Report
When using if-statements, the type is being properly narrowed depending on the conditions checked. mypy seems unable to do the same type of narrowing in a match statement
from typing import Literal, TypeAlias
Expr: TypeAlias = (
tuple[Literal['lit'], int] |
tuple[Literal['var'], str]
)
def square_lits(expr: Expr) -> Expr:
match expr:
case ('lit', x):
return ('lit', square(x))
case _:
return expr
def square(x: int) -> int:
return x * xHere I get an error:
test.py:11: error: Argument 1 to "square" has incompatible type "int | str"; expected "int" [arg-type]
Found 1 error in 1 file (checked 1 source file)
While the following works fine:
https://mypy-play.net/?mypy=latest&python=3.12&gist=ab7f28a259a5bff450413ce2f2924e74
from typing import Literal, TypeAlias
Expr: TypeAlias = (
tuple[Literal['lit'], int] |
tuple[Literal['var'], str]
)
def square_lits(expr: Expr) -> Expr:
if expr[0] == 'lit':
return ('lit', square(expr[1]))
return expr
def square(x: int) -> int:
return x * xExpected Behavior
Both examples should work fine without any typechecking errors
Actual Behavior
Mypy is not able to narrow the type in the match statement case like it is able to when using if-conditions
Your Environment
The mypy playground links (mypy version 1.11.0, Python version 3.12).
Related:
Reacted by Connor Brinton
Activity
bergkvist commentedon Jul 27, 2024
This seems to be where the if statement types are narrowed into
tuple[Literal['lit'], int]andtuple[Literal['var'], str]:mypy/mypy/checker.py
Line 4638 in 8b74b5a
Prabhat-Thapa45 commentedon Aug 26, 2024
Nice finding.
matchbeing a relatively new feature, i.e., in 3.10 Python, might be one reason for mypy to fail or not being mature enough to handle this. Also, it can be relatively complex to handle this, although you have come up with a very straightforward example above but I can imagine it should be quite a task to achievedistrame commentedon Dec 25, 2024
I encountered a similar bug. Do not know if current PR #17600 solves it.
Below example shows errors from mypy 1.14.0
Further improve match statement narrowing against unions (python#20744)