isinstance check widens type
Open
Nobody has claimed this yet.
bug
topic-type-narrowing
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
- 2025-02-14: reproduced using mypy 1.15 and python 3.13 mypy-playground
- 2023-02-14: reproduced using mypy 1.0 and python 3.11 mypy-playground
from collections.abc import Collection, Mapping
def f(x: int | Collection[int] | Mapping[str, int]) -> int:
r"""Recursively sum up all the values of possibly nested data."""
if isinstance(x, int):
return x
if isinstance(x, Mapping):
return sum(f(y) for y in x.values())
reveal_type(x) # <- Here, mypy thinks this is Collection only!
if isinstance(x, Collection):
reveal_type(x) # <- Suddenly mypy thinks this is Collection | Mapping
return sum(f(y) for y in x) # ❌ "f" has incompatible type "int | str"
raise TypeError(f"unsupported type: {type(x)}")
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.
Research direction
Start by running the provided reproducer in the linked mypy-playground examples with the listed mypy and Python versions, then trace how the isinstance checks narrow x after the Mapping branch. Done means the Collection branch narrows x consistently and the shown call to f passes type checking without the incompatible int | str error.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers, devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100