Skip to content

mypy does not deduce more specific type of generic based on isinstance of attribute #8435

@osandov

Description

@osandov

The following code:

from dataclasses import dataclass
from typing import Generic, TypeVar, Union


T_co = TypeVar("T_co", covariant=True)
@dataclass(frozen=True)
class Foo(Generic[T_co]):
    bar: T_co


def handle_foo_int(foo: Foo[int]) -> None:
    pass


def handle_foo(foo: Foo[Union[int, str]]) -> None:
    if isinstance(foo.bar, int):
        handle_foo_int(foo)

Results in the following error from mypy:

$ mypy test.py
test.py:17: error: Argument 1 to "handle_foo_int" has incompatible type "Foo[Union[int, str]]"; expected "Foo[int]"

If foo.bar is an int, it seems to me that it should imply that foo is a Foo[int]. Is there a way to get mypy to deduce that?

I tested this on 0.761 and 0.770+dev.7af3191246c17a8580acd3b6336f35b02de85e7e.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions