python / mypy

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

Callable type anntoation written apart of assignment causes false positive typecheck result. #8521

Open Renegatto opened 4 years ago

Renegatto commented 4 years ago

A bugreport, mypy version is 0.761, python version is 3.7.3

This is a case where expected incapatible types, because i declared that foo's input type is float, and attempting to call it with str, but typechecking passed successful.

from typing import Callable

def bar(x):  return 5

foo : Callable[[float],int]
foo = bar

foo("test")

mypy this_file.py Mypy's output:

Success: no issues found in 1 source file

A case with type annotation written with assignment wont give false positive result:

from typing import Callable

def bar(x):  return 5

foo : Callable[[float],int] = bar

foo("test")

mypy this_file.py Mypy's output:

this_file.py:7: error: Argument 1 has incompatible type "str"; expected "float" Found 1 error in 1 file (checked 1 source file)

I wasnt found other cases excluding cases with Callable type.

For example with Tuples type anntoation written apart of assignment all working fine:

from typing import Tuple

foo : Tuple[str,int]
foo = (1,3)

mypy this_file.py Mypy's output:

this_file.py:4: error: Incompatible types in assignment (expression has type "Tuple[int, int]", variable has type "Tuple[str, int]") Found 1 error in 1 file (checked 1 source file)

msullivan commented 4 years ago

If any part of this is wrong, it is that part 1 doesn't result in an error. The type of foo there gets refined to def (x: Any) -> Any, which seems wrong to me, since we mostly don't do that with other types?

Our exact behaviors regarding Any and type refinement are sort of unclear and pretty heuristic

msullivan commented 4 years ago

@JukkaL thoughts?

JukkaL commented 4 years ago

The way type refinement works is inconsistent. Deciding what's the best fix is non-trivial however, since we don't want generate too many new false positives or negatives.

8540 is related (and there are probably other related issues).