python / python/mypy

Type checking fails to distribute across Tuple types

Open
#18,922 10 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

Union types fail to distribute across Tuple types as they ought to when the set of concrete values of each type are identical.

To Reproduce

(https://mypy-play.net/?mypy=latest&python=3.12&gist=9d0052b0ed30856e5ad3985237f8754b)

from typing import Union, Tuple, Optional

def id(x: Tuple[float, Optional[float]]) -> Union[Tuple[float, float], Tuple[float, None]]:
    return x

Expected Behavior

Values of type Tuple[float, Optional[float]] and Union[Tuple[float, float], Tuple[float, None]] should be mutually compatible.

That is: Union ought to distribute across Tuple.

Actual Behavior

main.py:4: error: Incompatible return value type (got "tuple[float, float | None]", expected "tuple[float, float] | tuple[float, None]")  [return-value]

Your Environment

(See Playground link.)

  • 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 by reproducing the example in the linked mypy-play playground or main.py and confirm the incompatible return type. Trace how mypy checks compatibility between Tuple[float, Optional[float]] and the union of tuple types. Done means the example type-checks without the reported return-value error and regression coverage preserves that behavior.

Written by the indexing model from the issue text.

Assessment

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