python / python/mypy

Mypy reports invalid type when a value is a parameterized generic

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

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

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

説明

Bug Report

When I attempt to use a parameterized generic as a value to build a signature at runtime, mypy complains about the parameter as being invalid, when the parameter comes from a variable.

To Reproduce

from inspect import Parameter

def signature_parameter(name: str, item_type: type) -> Parameter:
    return Parameter(name=name, kind=Parameter.KEYWORD_ONLY, annotation=list[item_type])

Expected Behavior

I would expect no error in this case (when the parameterized type is used as a value).

I know a variable cannot be used as a type parameter in a typing context (i.e. when used as a type annotation).
I understand that the following code would be wrong because variables cannot be used in type specifications:

var: type = int
lst: list[var] = [1, 2, 3]  # this is wrong

But in my case above, list[item_type] is not used as a type specification, but as a value, that is passed to the runtime to build a signature. I do not think mypy should flag such use of values. It should simply consider the value to be of type types.GenericAlias.

Actual Behavior

typing-8.py:6: error: Variable "item_type" is not valid as a type  [valid-type]
typing-8.py:6: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 1.12.0+dev.6a0657e5959ba1777c4d427f8f355d499035d145 (compiled: no)
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files):
[tool.mypy]
enable_incomplete_feature = "NewGenericSyntax"
disable_bytearray_promotion = true
disable_memoryview_promotion = true
check_untyped_defs = true
warn_unreachable = true
warn_redundant_casts = true
warn_unused_ignores = true
  • Python version used: 3.12

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

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

はじめの一歩

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

調査の方向性

typing-8.py の再現コードから始め、Python 3.12 で mypy を実行して、list[item_type] に対する [valid-type] 診断を確認します。この診断の原因となっている型チェックの経路を追跡し、この実行時アノテーション値が受け入れられることを示す回帰テストを追加します。エラーを抑制せずにテストが通れば完了です。

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

評価

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

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

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