python / python/mypy

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

Open
#8,435 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

false-positive feature priority-2-low topic-type-narrowing
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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.

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 reproducer in test.py and run it with mypy to confirm the reported error. Investigate how isinstance checks on attributes interact with generic type narrowing; done means the example can pass Foo[Union[int, str]] to handle_foo_int after the check without the incompatible-type error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.