python / python/mypy

Incorrect narrowing between two different unions

Open
#20,820 2 comments 0 reactions 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

Bug Report

Narrowing via isinstance and two unions does not seem to do a full crossproduct of possibilities. Spotted when reviewing https://github.com/python/mypy/pull/20743.

To Reproduce

from __future__ import annotations

class A: ...

class B: ...

class C: ...

def f1(x: A | C, t: type[A] | type[B]):
    if isinstance(x, t):
        reveal_type(x)  # N: Revealed type is "__main__.A"
    else:
        reveal_type(x)  # Revealed type is "__main__.A | __main__.C"

Expected Behavior

I would expect the revealed types to be a superset of the results if we did a crossproduct. However, note that <subclass of C and B> is missing. (probably the best way to express this would be to have intersections but... yeah...)

Actual Behavior

Positive branch just has A.

Your Environment

Reproduced in mypy-play

  • Mypy version used: master
  • Mypy command-line flags: N/A
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.12

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 supplied Python reproducer in mypy-play using mypy master and Python 3.12, then trace the isinstance narrowing behavior in mypy. Done means the positive and negative reveal_type results account for the full crossproduct described in Expected Behavior, including the missing subclass-of-C-and-B possibility.

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
Quiet
Clarity
Mostly clear
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.