python / python/mypy

MyPy should report error if variable imported in TYPE_CHECKING block?

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

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

feature priority-1-normal topic-runtime-semantics
主要言語
Python
スター
20.6k
フォーク
3.3k
平均マージ
1日 18時間
マージ済み PR(30日)
54

説明

Currently, MyPy doesn't report an error when a variable is imported in the if TYPE_CHECKING block and then used elsewhere.
For example, MyPy accepts this code:

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from typing import NamedTuple

class C(NamedTuple):
    x: int
    y: int

even though, at runtime, it fails:

Traceback (most recent call last):
  File "type_checking_test.py", line 6, in <module>
    class C(NamedTuple):
NameError: name 'NamedTuple' is not defined

(I'm using MyPy version 0.650.)

Should this be fixed? I think this could be fixed by adding an is_type_checking_only variable to SymbolTableNode, which is True if the variable was imported or assigned within a TYPE_CHECKING block, and ensuring that this flag is false for any variables used in places other than type annotations in the actual code.

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

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

はじめの一歩

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

調査の方向性

まず、提示された TYPE_CHECKING と NamedTuple の例で問題を再現し、次に TYPE_CHECKING ブロック内のインポートとシンボルテーブルエントリがどのように扱われるかを追跡します。MyPy が実行時に無効な使用を報告しつつ、型アノテーションでのみ使用される名前は引き続き許可するようになり、その例の動作をカバーするテストがある状態で作業完了です。

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

評価

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

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

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