python / python/mypy

Type narrowing on object attribute with match statement doesn't apply

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

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

feature topic-match-statement topic-type-narrowing
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

The bug
It seems that doing a "type checking" with the object UI in pattern matching seems to not work properly.
Attribute match is not considered.

Code

class Test:
    def __init__(self, a: int | str):
        self.a: int | str = a

test = Test(5)

match test:
    case Test(a = int()):
        print(test.a + 3)
    case Test(a = str()):
        print(test.a + "3")

Expected behavior
By doing a match with Test(a = int()), python will check test is of type Test AND test.a is of type int.
But mypy "only assert" that test if of type Test. It keep the type int | str for test.a.

Reproduce :
On mypy-playground :
https://mypy-play.net/?mypy=latest&python=3.11&gist=6f05124abd1ef68032d59651a7d5c6c3

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

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

はじめの一歩

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

調査の方向性

issue にリンクされている mypy-playground の再現例から始め、match 文が Test(a=int()) および Test(a=str()) パターンをどのように処理するかを追跡します。各分岐での test.a の推論された型を比較します。完了条件は、属性がそれぞれ int または str に絞り込まれ、その動作が回帰テストでカバーされていることです。

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

評価

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

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

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