python / python/mypy

Assignment via `import`

Open
#12,965 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-type-narrowing
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the two inline Python reproductions with mypy 0.950 and compare the reported errors for local and global imports. Trace how these import aliases are analyzed, then add regression coverage showing the callable is recognized after the conditional import and that the erroneous diagnostics are gone.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.