python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.3k stars 2.8k forks source link

bad error message when attempting to assign to generic type #11536

Open DetachHead opened 2 years ago

DetachHead commented 2 years ago
from typing import TypeVar

T = TypeVar("T", int, str)

def foo() -> T:
    return 1 # error: Incompatible return value type (got "int", expected "str")  [return-value]

def bar() -> T:
    return "" # error: Incompatible return value type (got "str", expected "int")  [return-value]

https://mypy-play.net/?mypy=latest&python=3.10&gist=442fc0f6332aa02d4dc509460b91536a

i think the error message should be something like:

Incompatible return value type (got "int", expected "T")

or maybe something more descriptive, like how typescript puts it:

'T' could be instantiated with an arbitrary type which could be unrelated to 'number'.

https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABMOcA8AVAfACgJQBciGiA3gLABQiNiATgKZQh1ICMVAvkA

erictraut commented 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.

JelleZijlstra commented 2 years ago

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.