python / python/mypy

type inference is fragile for protocols like SupportsKeysAndGetItem

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

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

主要言語
Python
スター
20.6k
フォーク
3.3k
平均マージ
1日 18時間
マージ済み PR(30日)
54

説明

Repro: https://mypy-play.net/?mypy=latest&python=3.11&gist=d2f8dfa1fdfda5c0c286f1a73f5e39eb

Pasted below for convenience:

import typing as t

from _typeshed import SupportsKeysAndGetItem


KT = t.TypeVar("KT")
VT = t.TypeVar("VT")


def version1(obj: SupportsKeysAndGetItem[KT, VT] | t.Iterable[tuple[KT, VT]]):
    if hasattr(obj, "keys") and hasattr(obj, "__getitem__"):
        reveal_type(obj)  # SupportsKeysAndGetItem[KT, VT] | Iterable[tuple[KT, VT]] (as expected)
    else:
        reveal_type(obj)  # narrowed to Iterable[tuple[KT, VT]] as expected


def version2(obj: SupportsKeysAndGetItem[KT, VT] | t.Iterable[tuple[KT, VT]]):
    if hasattr(obj, "keys") and hasattr(obj, "__getitem__") and (obj_getitem := obj.__getitem__):
        reveal_type(obj)  # SupportsKeysAndGetItem[KT, VT] | Iterable[tuple[KT, VT]] (as expected)
    else:
        reveal_type(obj)  # NOT narrowed

I would expect version 2 to behave the same as version 1. Is that an improvement mypy could reasonably make?

I searched for relevant docs and existing issues, but didn't find anything specifically about this. Apologies if I missed something.

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

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

はじめの一歩

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

調査の方向性

リンクされている mypy-play の再現コードを実行し、version1 と version2 の reveal_type の結果を比較します。組み合わせた hasattr チェックと walrus 代入に対する型の絞り込みロジックを追跡します。version2 が version1 と一貫して else ブランチを絞り込み、その例のリグレッションカバレッジがあることを完了条件とします。

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

評価

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

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

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