mypy does not deduce more specific type of generic based on isinstance of attribute
Nobody has claimed this yet.
Assessment
- Difficulty
- 5/5
- Estimated time
- Over a week
- Newbie friendliness
- 35/100
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.
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.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- Avg merge
- 1d 18h
- Merged PRs (30d)
- 54
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from python/mypy
-
bug
Difficulty 2/5 1-3 hours Newbie friendliness 75/100
-
bug
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
-
bug
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
-
documentation
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
-
bug topic-configuration topic-error-reporting
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
Similar issues
-
Difficulty 2/5 1-3 hours Newbie friendliness 74/100
bancolombia/sentinel#23 ·
-
test md OpenCI
Difficulty 2/5 1-3 hours Newbie friendliness 74/100
-
integration:quickjs org:external priority:backlog topic:code-interpreter topic:middleware type:feature
Difficulty 2/5 1-3 hours Newbie friendliness 74/100
langchain-ai/deepagents#6450 ·
-
bug client
Difficulty 2/5 1-3 hours Newbie friendliness 88/100
-
Difficulty 2/5 1-3 hours Newbie friendliness 74/100