python / python/mypy

Return type hint fails with multiple supplied type vars

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

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

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

説明

Bug Report

I'm not 100% sure how to word this but mypy fails to detect the proper return type if multiple types are supplied. It works just fine if only a single type is specified.

This scenario works just fine with pyright/pylance.

To Reproduce

import typing as t


class BaseClass:
    ...


class Sub1(BaseClass):
    ...


class Sub2(BaseClass):
    ...


ClassType = t.TypeVar("ClassType", bound=BaseClass)


def testing_union() -> t.Union[Sub1, Sub2]:
    res = sub_method(Sub1, Sub2)
    reveal_type(res)

    return res


def testing_single() -> Sub1:
    res = sub_method(Sub1)

    return res


def sub_method(*output_type: t.Type[ClassType]) -> ClassType:
    return  # type: ignore[return-value]

Expected Behavior

I expect mypy to work for both testing_union() and testing_single().

Actual Behavior

A return-value occurs in testing_union as it thinks the value is the bound base class. Using reveal_type we can see that mypy detects the type as BaseClass whereas pylance/pyright detects it as the expect3ed Sub1 | Sub2 type.

image

The output from the mypy check is

mypy-test.py:21: note: Revealed type is "mypy-test.BaseClass"
mypy-test.py:23: error: Incompatible return value type (got "BaseClass", expected "Union[Sub1, Sub2]")  [return-value]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 1.0.0 (compiled: yes)
  • Mypy command-line flags: python -m mypy file.py
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: Python 3.11.0

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

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

はじめの一歩

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

調査の方向性

まず、提供された再現コードを mypy 1.0.0 で実行し、複数の型引数の場合と単一の型引数の場合で明らかになる型を比較します。sub_method の可変長 TypeVar 引数に対する型推論の挙動を追跡します。union ケースで Sub1 | Sub2 が明らかになり、単一型のケースを弱めることなく宣言された戻り値のチェックに合格すれば完了です。

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

評価

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

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

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