python / python/mypy

Function "issubclass()" incorrectly narrows down a type of variable. Generic. TypeVar. Subclass.

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

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

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

説明

Bug Report

Function "issubclass()" does not narrow down a type of variable.

To Reproduce

from typing import Any, Generic, TypeVar, cast

R = TypeVar("R", "FooResponse", "BarResponse")


class BaseResponse:
    def __str__(self) -> str:
        return "<{}: {}>".format(self.__class__.__name__, self.__dict__)


class FooResponse(BaseResponse):
    def __init__(self, val: str) -> None:
        self.foo1 = val


class BarResponse(BaseResponse):
    def __init__(self, val1: str, val2: str) -> None:
        self.bar1 = val1
        self.bar2 = val2


class BaseRequest(Generic[R]):
    response_class: type[R]


class FooRequest(BaseRequest[FooResponse]):
    response_class = FooResponse


class BarRequest(BaseRequest[BarResponse]):
    response_class = BarResponse


def build_data(response_class: type[R]) -> R:
    if issubclass(response_class, FooResponse):
        reveal_type(response_class)
        return FooResponse("FOO")
    raise ValueError("Unsupported type: {}".format(response_class))


def query(req: BaseRequest[R]) -> R:
    return build_data(req.response_class)


def main(**_kwargs: Any) -> None:
    print(query(FooRequest()))

I expect mypy does not throw any error while validating the source code.

Actual Behavior

I got this output:

script/test_union.py:36: note: Revealed type is "Type[script.test_union.FooResponse]"
script/test_union.py:36: note: Revealed type is "Type[script.test_union.<subclass of "BarResponse" and "FooResponse">]"
script/test_union.py:37: error: Incompatible return value type (got "FooResponse", expected "BarResponse")  [return-value]

Your Environment

Versions:

Python 3.11.1
mypy==1.2.0
mypy-extensions==1.0.0

Mypy command: mypy --strict mysourcecode.py

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

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

はじめの一歩

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

調査の方向性

インラインの Python reproducer から始め、報告されたバージョンで mypy --strict mysourcecode.py を使って実行します。明らかになった型と戻り値のエラーを期待される動作と比較します。reproducer が互換性のない戻り値エラーなしで検証され、正しいジェネリックの絞り込みが維持されれば完了です。

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

評価

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

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

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