Skip to content

Allow variables in iterable-unpacking assignment to narrow together #1850

Description

@benblank

Description

I don't know whether this is feasible, but it would be very convenient if variables used in the same iterable-unpacking assignment were "linked" in some way which would make it possible for narrowing the type of one to narrow the type of the other(s).

For example, if a function is typed as returning tuple[int, int] | tuple[None, None] and its return value is unpacked, narrowing one of the unpacked values to not None would ideally narrow the other, as well.

from random import random
from typing import reveal_type


def get_tuple() -> tuple[int, int] | tuple[None, None]:
    if random() < 0.5:
        return 1, 2

    return None, None


first, second = get_tuple()

if first is not None:
    reveal_type(first)   # Reveals "int".
    reveal_type(second)  # Reveals "int | None", but "int" would be better.

(playground link)

Both Pyright and Mypy currently behave in the same manner as Basedpyright, so I assume this isn't trivial. 😅

Metadata

Metadata

Assignees

No one assigned

    Labels

    type checking / lintingissues relating to existing diagnostic rules or proposals for new diagnostic rules

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions