python / python/mypy

Incorrect widening of `T | None` with unions to `builtins.object` in generic functions

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

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

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

説明

Bug Report

Generic function with signature (fun: Callable[[], T | None]) -> T | None has its type incorrectly widened to builtins.object when T is a union type

To Reproduce

import typing

T = typing.TypeVar("T")


def gen_fun_one(fun: typing.Callable[[], T | int]) -> T | int:
    return fun()


def gen_fun_two(fun: typing.Callable[[], T | None]) -> T | None:
    return fun()


def foo() -> int | str | None:
    pass


typing.reveal_type(gen_fun_one(foo))  # Union[builtins.str, None, builtins.int]
typing.reveal_type(gen_fun_two(foo))  # builtins.object

Gist URL: https://gist.github.com/mypy-play/f2401bd493520f4c72cad4a416195e19
Playground URL: https://mypy-play.net/?mypy=latest&python=3.12&gist=f2401bd493520f4c72cad4a416195e19

Expected Behavior

Both gen_fun_one(foo) and gen_fun_two(foo) are of type str | int | None

Actual Behavior

Function gen_fun_two(foo) is of type builtins.object

Your Environment

  • Mypy version used: 1.9.0
  • Python version used: 3.12
  • Default Mypy playground settings

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

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

はじめの一歩

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

調査の方向性

まず、リンク先の mypy playground にある提供済みの Python 再現コードを実行し、gen_fun_one と gen_fun_two の reveal_type の結果を比較します。2 回目の呼び出しに関係するジェネリックな union の推論を追跡します。報告されたケースのカバレッジを含め、builtins.object ではなく str | int | None と推論されれば作業完了です。

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

評価

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

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

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