python / python/mypy

Unions of `TypedDict` turn into intersections in some generic functions

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

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

bug
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

Bug Report
When passing unions of TypedDict to certain generic functions, mypy deduces their type to be the intersection of the TypedDicts, and not the union.

Discovered here.

To Reproduce

from typing import TypedDict, TypeVar

class A(TypedDict):
    shared: str
    different: str

class B(TypedDict):
    shared: str
    different: int
    extra: int

T = TypeVar("T")
def f(a: T, b: T) -> T:
    return b

def g(a: T | None, b: T) -> T:
    return b

c: A | B
d: A | B

r1: A | B = f(c, d)  # passes
r2: A | B = g(c, d)  # expression has type "TypedDict({'shared': str}) [assignment]

Expected Behavior
g(c, d) should have type A | B and not {"shared": str}.

Actual Behavior

mypy_error.py:23: error: Incompatible types in assignment (expression has type "TypedDict({'shared': str})", variable has type "Union[A, B]")  [assignment]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 1.0.0 (compiled: yes)
    • Same error on mypy 0.800, Python 3.10.9
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: Python 3.10.9

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

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

はじめの一歩

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

調査の方向性

まず issue の最小限の Python 再現コードを実行し、f(c, d) と g(c, d) の推論された型を比較します。TypedDict のユニオンに対する mypy のジェネリック型推論を追跡し、次に例を対象とするリグレッションテストを追加して、g(c, d) が A | B として受け入れられることを確認します。

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

評価

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

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

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