Generic `NamedTuple` does appear attribute-less in `match` statements, and member type information is erased
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
Bug Report
If a NamedTuple is generic over T, then for some reason, inside a match statement over this NamedTuple, all information about member variables and their types are erased. Even if they are explicitly stated.
To Reproduce
from typing import NamedTuple
class Wrapper[T](NamedTuple):
wrap: T
foo: Wrapper[int] = Wrapper(123)
def bar() -> int:
match foo:
case Wrapper(wrap=w):
return w
case _: # this is only to make this error-less with `pyrefly`
raise RuntimeError("Unreachable")
Expected Behavior
This function clearly matches a Wrapper[int] in its first case. It should detect it can match the internal wrap variable, and it also has to be int.
$ pyrefly check tst.py
INFO 0 errors
$ pyright tst.py
0 errors, 0 warnings, 0 informations
Actual Behavior
mypy for some reason seems to say that Wrapper does not even have a wrap attribute, and also, it's saying that this is Any, even though the matched Wrapper here is Wrapper[int].
$ mypy --strict tst.py
tst.py:12: error: Class "tst.Wrapper[Any]" has no attribute "wrap" [misc]
tst.py:13: error: Returning Any from function declared to return "int" [no-any-return]
Your Environment
- Mypy version used: 1.19.1
- Mypy command-line flags:
--strict - Python version used: 3.12.9
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
Python 3.12.9 と mypy --strict を使用して tst.py の報告を再現し、その後、示されているように結果を pyrefly および pyright と比較します。match 文内の汎用 NamedTuple パターンがどのように解析されるかを追跡します。w が型 int の wrap 属性として認識され、例でエラーが報告されなければ完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- devtools
- issue の種類
- バグ
- 難易度
- 3/5
- 見積もり時間
- 1〜2日
- 活発さ
- 停滞
- 明瞭さ
- 明確に書かれている
- 初心者へのやさしさ
- 48/100