python / python/mypy

tuple element types wrongly mixed as union

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

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

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

説明

Bug Report

When a variable conditionally gets one or the other of a set of fixed-length tuples, instead of being inferred as a union of said tuple types, mypy sees an arbibrary-length tuple whose elements are typed with a union of all element types involved. This results false-positive errors being reported.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.12&gist=4780da0a891d33c46ee7ac0b55a05f24

Expected Behavior

Similar to what pyright reveals, a union of two tuple types with defined length and element types, and no error when assigning :

  /home/user/omaha/omaha/uitest/mypy-test.py:9:17 - information: Type of "item" is "tuple[Literal[1], Literal['a'], list[bool]] | tuple[Literal[1], Literal['a']]"

Actual Behavior

The type is instead inferred to be a tuple of arbitrary length, with all elements allowed to have any of the types seen inside the tuple:

main.py:9: note: Revealed type is "builtins.tuple[builtins.int | builtins.str | builtins.list[builtins.bool], ...]"
main.py:10: error: List item 0 has incompatible type "tuple[int | str | list[bool], ...]"; expected "tuple[int, str] | tuple[int, str, Sequence[bool]]"  [list-item]

Note that when using just item = (1, "a"), removing the conditional part, the tuple is properly identified with fixed types, and the assignment is validated by mypy:

main.py:9: note: Revealed type is "tuple[builtins.int, builtins.str]"

Your Environment

  • Mypy version used: 1.18.2
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.12, 3.14.0rc2

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

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

はじめの一歩

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

調査の方向性

まず、リンクされている mypy-play の再現例を mypy 1.18.2 で実行し、表示された型と代入の診断を、期待される pyright の結果と比較します。条件付き代入に関係するタプル推論の挙動を追跡します。固定長タプルの選択肢がユニオンのまま保持され、示された代入で誤検知が発生しなくなれば完了です。

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

評価

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

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

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