python / python/mypy

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

オープン
#7,419 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

bug priority-1-normal semantic-analyzer topic-import-cycles
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

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.

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

用意されている testImportCycleWithOverriddenName ケースから始め、--strict --no-incremental を付けて実行します。package/init.py、package/a.py、package/b.py を比較し、特に import の順序と from . import a 文を確認します。init.py の 2 行を入れ替えた場合も ModuleType の結果を維持しながら、reveal_type(a) が builtins.str を報告すれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
compilers, devtools
issue の種類
バグ
難易度
3/5
見積もり時間
1〜2日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
45/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。