python / python/mypy

Overeager type narrowing

Open
#13,946 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

I'm implementing type narrowing and thinking about intersection types for Python in general and I noticed this behavior in mypy:

Point = tuple[int, int]

class Shape: pass

def scale(x: float, o: int | Point | Shape):
  if isinstance(o, tuple):
    reveal_type(o)

Will show Tuple[builtins.int, builtins.int] which might seem reasonable but what if there's

class ColorShape(Shape, tuple[Shape, str]): pass

We should say that the intersection of Point and tuple (= tuple[Any, ...]) is Point (= tuple[int, int]). The intersection of Shape and tuple is not known to be empty.

The intersection of int and tuple is known to be empty for CPython because:

>>> class A(int, tuple): pass
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: multiple bases have instance lay-out conflict

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 inline mypy example and checking the revealed type for the isinstance(o, tuple) branch. Trace the type-narrowing behavior for the Point, Shape, and int union members; done means narrowing preserves possible tuple intersections without treating unrelated or potentially compatible types as impossible.

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.