python / python/mypy

mypy accepts invalid PEP 604 syntax with forward reference

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

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

feature topic-pep-604 topic-runtime-semantics
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

Bug Report

PEP 604 introduced the | syntax, however it's not entirely equivalent to the Union syntax. Forward references with | are not supported and result in TypeErrors TypeError: unsupported operand type(s) for |: 'type' and 'str'. Mypy doesn't warn the user about this and accepts | with forward references.

To Reproduce

T = list[int | "T"]

Playground

Expected Behavior

Some kind of error telling me that this syntax is not supported.

Actual Behavior

No errors reported.

Your Environment

  • Mypy version used: 0.991
  • Mypy command-line flags: --strict or no flags, doesn't matter
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.11

I originally raised this as a discussion in pyright repo. And since then pyright has implemented https://github.com/microsoft/pyright/commit/6eb846709f4fec0180593f3e89f1dd5b20f41956 to detect this incorrect usage of | (available in release 1.1.285). I have to admit that documentation on this is a bit murky as I was expecting | to be equivalent to Union and I wasn't the only one, see https://github.com/python/cpython/issues/90015. From what I can gather in this CPython issue runtime won't be changed to make this syntax valid and docs should be changed instead (but neither happened yet).

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

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

はじめの一歩

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

調査の方向性

まず、提供された再現コード T = list[int | "T"] に対して mypy を実行し、PEP 604 の union における前方参照がどのように解析されるかを追跡します。この例の回帰テストを追加し、妥当な union の処理を維持しながら、構文がサポートされていないと mypy が報告することを確認します。

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

評価

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

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

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