Open DetachHead opened 2 years ago
I think this is a side effect of the way mypy analyzes generic functions that are parameterized by one or more constrained TypeVars. It analyzes the function multiple times, once for each combination of possible constraints.
For example, you'll receive two error messages here:
T = TypeVar("T", int, str)
def foo() -> T:
return 1.0
# error: Incompatible return value type (got "float", expected "int")
# error: Incompatible return value type (got "float", expected "str")
And four error messages here:
S = TypeVar("S", int, str)
T = TypeVar("T", int, str)
def foo() -> Union[T, S]:
return 1.0
# error: Incompatible return value type (got "float", expected "int")
# error: Incompatible return value type (got "float", expected "Union[int, str]")
# error: Incompatible return value type (got "float", expected "Union[str, int]")
# error: Incompatible return value type (got "float", expected "str")
I don't disagree with your point that the error messages are confusing. I'm just saying that improving the errors would likely require a significant change to mypy's semantic analyzer logic.
We could probably improve the error messages without totally changing how we check this code, just by setting some state that the error message generation code reads.
https://mypy-play.net/?mypy=latest&python=3.10&gist=442fc0f6332aa02d4dc509460b91536a
i think the error message should be something like:
or maybe something more descriptive, like how typescript puts it:
https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABMOcA8AVAfACgJQBciGiA3gLABQiNiATgKZQh1ICMVAvkA