python / python/mypy

Spurious redef warning in an odd situation with type(None) plus TypeAlias plus a later # type: ignore

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

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

bug
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

Really bizarre behavior here that I can't figure out. Probably not high priority as it's likely an extreme edge case.

This code:

from typing import TypeAlias

abc: TypeAlias = type(None)

x = y # type: ignore

generates the following error in mypy 1.10.1 running on Python 3.11.8:

tt.py:3: error: Name "abc" already defined on line 3  [no-redef]
Found 1 error in 1 file (checked 1 source file)

This is obviously wrong, as abc is not a redefinition (and you can rename it to whatever you want, you get the same error).

This error does NOT happen if you do any of the following:

  1. Use type instead of TypeAlias as the declared type of abc.
  2. Use any value other than type(None) as the value of the expression (if you use type(5), for example, you get the slightly more reasonable although still inaccurate error message that the expression isn't a valid type; I think it's reasonable to expect type literals only rather than at-runtime types though, so this is understandable.
  3. If you don't include the last line which generates a second mypy error (in that case, you get NO error on the abc line, not even the "not a valid type" error you'd get for assigning to type(5)).

The presence of the # type: ignore comment is optional as it turns out, it doesn't matter whether the second error is generated or suppressed, just that there is a second error in the file.

What should happen? IDK fix the underlying bug here. Probably we should get a "not a valid type" error similar to the type(5) situation, and of course that should happen regardless of whether there are or aren't errors elsewhere in the file.

Workaround: import NoneType from the types module is probably cleanest.

I'll mention here for others who might find this looking for how to use NoneType as a type annotation that you'll get a warning from mypy if you use NoneType as a type hint, saying you should use None instead (and yo should probably do that). The code that inspired this used NoneType not as a type hint but for a runtime isinstance check.

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

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

はじめの一歩

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

調査の方向性

まず、mypy 1.10.1 で報告にある最小限の Python スニペットを使って問題を再現し、次に TypeAlias、type(None)、後続の無視された代入がある場合とない場合の動作を比較します。エイリアスと、後続のエラーを発生させる行の処理を追跡します。他のエラーの有無にかかわらず一貫した invalid-type 診断が出力され、余分な no-redef エラーが発生しなければ完了です。

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

評価

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

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

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