python / python/mypy

Parameter TypeVar unexpectedly becomes optional when unpacking call results

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

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

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

説明

Bug Report

When calling a generic function mypy unexpectedly introduces optionality in the TypeVar when the result is unpacked and raises an error on a perfectly valid function call:

from typing import Iterable


def fun[T](values: Iterable[T], value: list[T]) -> tuple[T | None, T | None]:
    ...
    return None, None


values: Iterable[int]
my_list: list[int]

result = fun(values, my_list)  # works fine
m, n = result

a, b = fun(values, my_list)  # raises error in mypy

Mypy error:

main.py:15: error: Argument 2 to "fun" has incompatible type "list[int]"; expected "list[int | None]"  [arg-type]

This has something to do with the return type of the function being a tuple of optional T's. If the return type is not a union with None or not a tuple, the error disappears.

To reproduce

Here is playground gist of the example: gist

Expected Behavior

In the example I expect both calls to be approved by mypy. Also, I don't expect unpacking to influence what arguments can given in a function call, at least not in this case.

Actual Behavior

mypy raises an error on the second call.

Your Environment

I used mypy playground to confirm this error in various versions:

  • Mypy version used: 1.17.1 1.18.2 master branch
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.12 3.13 3.14

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

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

はじめの一歩

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

調査の方向性

issue の最小限の generic-function 例から始め、報告されている Python のバージョンと構成で mypy に対して実行します。タプルのアンパックとオプショナルな TypeVars に関する型推論を追跡します。両方の呼び出しが、互換性のない list[int | None] の期待を導入することなく受け入れられれば完了です。

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

評価

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

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

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