python / python/mypy

Destructured tuple discrimination

Open
#13,816 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Feature

Destructured tuple discrimination

Pitch

Mypy shoud be able to discriminate between a union of structured types like tuples after destructuring.

import typing as t
from typing_extensions import reveal_type

ResultTup = t.Union[t.Tuple[int, None], t.Tuple[None, ValueError]]


def f(x: int) -> ResultTup:
    if x < 0:
        return None, ValueError("x must be positive")
    else:
        return x + 1, None


# NO DESTRUCTURING WORKS AS EXPECTED
result = f(1)
if result[1] is not None:
    ...
else:
    # mypy: Revealed type is "builtins.int"
    print(reveal_type(result[0]))

# DESTRUCTURING LOSES ASSOCIATION
ok, error = f(1)
if error is not None:
    ...
else:
    # mypy: Revealed type is "Union[builtins.int, None]"
    print(reveal_type(ok))

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 issue's Python example and compare the revealed types for indexed access with those after destructuring. Trace the type-checking path for union narrowing and tuple destructuring; done means the association between the destructured values is preserved so checking error narrows ok to int.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.