python / python/mypy

nested isinstances lose type information

Open
#10,146 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug false-positive topic-join-v-union topic-type-narrowing topic-union-types
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

To Reproduce

x = object()
if isinstance(x, (int, str)):
    reveal_type(x)      # Union[int, str]
    if isinstance(x, int):
        pass
    reveal_type(x)      # object

Expected Behavior

both types revealed as Union[int, str]

Actual Behavior

object from second type

Your Environment

  • Mypy version used: latest master (0.820+dev.72ac2cee910ca61bfdf449217328b6d10b45d378)
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.7.3
  • Operating system and version: debian 10 based linux distro

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

Use the provided Python reproducer as a regression case and inspect mypy's existing tests for isinstance-based type narrowing. The fix is complete when both reveal_type calls retain Union[int, str], with the surrounding narrowing behavior still covered by tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
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.