python / python/mypy

Wrong type inferred for a name conflicting with a module name in an import cycle

Open
#7,419 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug priority-1-normal semantic-analyzer topic-import-cycles
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

The following is a failing test case which demonstrates the issue. In runtime, the type of a that is printed is str, however mypy reveals the type _importlib_modulespec.ModuleType.

[case testImportCycleWithOverriddenName]
# flags: --strict --no-incremental
import package

[file package/__init__.py]
a = 'a from __init__'
from .b import B

[file package/a.py]

[file package/b.py]
from . import a
class B: pass
print(type(a))
reveal_type(a)

[out]
package/b.py:4: note: Revealed type is 'builtins.str'

Note that if the two lines in __init__.py are swapped, the runtime type is indeed ModuleType.

I did not look at the code, but my uneducated guess is that the current "state" of __init__.py is not consulted when the from . import a in b.py is processed. This can probably be reduced further.

  • mypy 0.720
  • Python 3.7.4

Spawned from issue #7393.

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 with the supplied testImportCycleWithOverriddenName case and run it with --strict --no-incremental. Compare package/init.py, package/a.py, and package/b.py, especially the import order and the from . import a statement. Done means reveal_type(a) reports builtins.str while preserving the ModuleType result when the two init.py lines are swapped.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.