Skip to content

Destructured tuple discrimination #13816

@reeseann

Description

@reeseann

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))

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions