python / python/mypy

list comprehensions: mypy fails to derive the union type for lists but not for tuples

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

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

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

説明

Bug Report

Inside a list comprehension mypy fails to derive the union type for lists but not for tuples.

To Reproduce

a = 5
b = "a_string"
list1: list[int | str] = [x for x in (a, b)]  # works
list2: list[int | str] = [x for x in [a, b]]  # fails

Expected Behavior

The same type should be derived for both lists.

Actual Behavior

The first list is recognised as list[int | str],
The second list is recognised as list[object],
Hence the error on line 4

❯ mypy mypy-repro.py                                                                                                                                                                                                               ─╯
mypy-repro.py:4: error: List comprehension has incompatible type List[object]; expected List[int | str]  [misc]
Found 1 error in 1 file (checked 1 source file)

Your Environment

❯ python --version                                                                                                                                                                                                                 ─╯
Python 3.11.8

❯ pip list | grep mypy                                                                                                                                                                                                             ─╯
mypy                  1.13.0
mypy-extensions       1.0.0

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

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

はじめの一歩

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

調査の方向性

まず、提供されている Python 3.11.8 の再現コードを mypy 1.13.0 で実行し、タプル式とリスト式の推論を比較します。リスト内包表記の型推論を追跡し、両方の式が同じ list[int | str] 型を導出するように、リグレッションテストを追加または更新します。

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

評価

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

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

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