python / python/mypy

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

Open
#15,046 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the inline Python reproducer and run it using mypy --strict mysourcecode.py under the reported versions. Compare the revealed types and return-value error with the expected behavior; done means the reproducer validates without the incompatible return error while preserving correct generic narrowing.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.