Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
lorien opened this issue Apr 13, 2023 · 0 comments
Labels
bug mypy got something wrong

Comments

@lorien
Copy link

lorien commented Apr 13, 2023

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

@lorien lorien added the bug mypy got something wrong label Apr 13, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

1 participant