python / python/mypy

isinstance check widens type

Open
#11,615 1 comment 1 reaction 0 assignees View on GitHub

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

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

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 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.