python / mypy

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

Assignment via `import` #12965

Open serhiy-storchaka opened 2 years ago

serhiy-storchaka commented 2 years ago

In the following example MyPy complain about local import and does not recognize it as assignment:

from typing import Callable, Optional

def f(callable: Optional[Callable[[float], float]]) -> None:
    if callable is None:
        from math import sqrt as callable  # line 5

    callable(1.5)  # line 7

Output:

t3.py:5: error: Name "callable" already defined on line 3
t3.py:7: error: "None" not callable
Found 2 errors in 1 file (checked 1 source file)

It is not recognized as assignment even for global import:

from typing import Callable, Optional

callable: Optional[Callable[[float], float]] = None
if callable is None:
    from math import sqrt as callable

callable(1.5)  # line 7

Output:

t32.py:7: error: "None" not callable
Found 1 error in 1 file (checked 1 source file)

mypy 0.950 (compiled: yes) Python 3.9.12

hauntsaninja commented 1 year ago

To clarify the state here, I fixed semantic analysis to not complain about the redefinition + get checker to type check it like an assignment. This gets rid of one of the errors here. However, we still need to fix the binder to do type narrowing here.