Union of Literals as key in union of TypedDict false positive

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

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

評価

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

調査の方向性

まず、提供されている Python 3.11 の再現コードを mypy に対して実行し、その後、Literal キーと TypedDict マッピングのユニオンに対する TypedDict キーの検証を追跡します。get_value_from_AB が誤検出なしで型チェックを通過し、単一辞書のケースも引き続き通過すれば完了です。

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

説明

bug topic-typed-dict topic-union-types

Bug Report
The function

def get_value(key: CombinedDictKey, mapping: CombinedDict):
    return mapping[key]

raises an error when mapping is a union of two TypedDicts and key is a union of two Literals containing the keys of those TypedDicts. It works when typed with just one of the Literals and TypedDicts.

To Reproduce

from typing import Literal, TypedDict, Union

class DictA(TypedDict):
    x: int
    y: int

class DictB(TypedDict):
    z: str

class DictAB(DictA, DictB):
    pass

DictAKey = Literal["x", "y"]
DictBKey = Literal["z"]
DictABKey = Union[DictAKey, DictBKey]

dict_a = DictA(x=1, y=2)
dict_b = DictB(z="z")
dict_ab = DictAB(**dict_a, **dict_b)  # type: ignore  # Unrelated issue #11108

def get_value_from_A(key: DictAKey, mapping: DictA):
    return mapping[key]  # Passes type check as expected

def get_value_from_B(key: DictBKey, mapping: DictB):
    return mapping[key]  # Passes type check as expected

def get_value_from_AB(key: DictABKey, mapping: DictAB):
    return mapping[key]  # Fails type check with error: TypedDict key must be a string literal

Expected Behavior
return mapping[key] passes typing in all three cases.

Actual Behavior
In the case of get_value_from_AB, return mapping[key] raises error: TypedDict key must be a string literal; expected one of ("z", "x", "y"). This is unexpected as it passes for the functions typed with only one of DictA or DictB.

Your Environment

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

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

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

はじめの一歩

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

python/mypy のほかの issue

python/mypy の issue をすべて見る

似ている issue

Python の issue をもっと見る

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

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