Open
Description
Bug Report
Mypy is unable to correctly handle type inference within generic functions that utilize the match expression, leading to type errors when returning different types of objects. In the provided example code, the match expression is used to match different classes and return corresponding instances.
To Reproduce
# test.py
from typing import TypeVar
from dataclasses import dataclass
@dataclass
class Test1:
a: int
@dataclass
class Test2:
b: int
T = TypeVar('T', Test1, Test2)
def f(t: T) -> T:
match t:
case Test1(a):
return Test1(a + 1) # error: Incompatible return value type (got "Test1", expected "Test2") [return-value]
case Test2(b):
return Test2(b - 1) # error: Incompatible return value type (got "Test1", expected "Test2") [return-value]
case _ as unreachable:
raise TypeError()
def g(t: T) -> T:
if isinstance(t, Test1):
return Test1(t.a + 1) # OK
elif isinstance(t, Test2):
return Test2(t.b - 1) # OK
else:
raise TypeError()
Expected Behavior
I expected mypy to correctly infer the return types of the f
function based on the match branches, and not produce type errors when returning instances of the corresponding types.
Actual Behavior
Function f
got an error, and function g
is OK. Also, pyright can't handle this problem.
Your Environment
- Mypy version used: mypy 1.5.1 (compiled: yes)
- Mypy command-line flags: mypy test.py
- Mypy configuration options from
mypy.ini
(and other config files): None - Python version used: Python 3.10.12 and Python 3.11.3