Skip to content

Cannot unpack Union of Tuples of different lengths #7965

Closed
@nielsbuwen

Description

@nielsbuwen
  • Are you reporting a bug, or opening a feature request?

I am reporting a bug.

  • Please insert below the code you are checking with mypy,
def unpack(two_or_three: Union[Tuple[int, int], Tuple[int, int, int]]) -> None:
    try:
        one, two = two_or_three
        three = None
    except ValueError:
        one, two, three = two_or_three
  • What is the actual behavior/output?

line:3: error: Too many values to unpack (2 expected, 3 provided)
line:6: error: Need more than 2 values to unpack (3 expected)

  • What is the behavior/output you expect?

The type checker should report no error.

  • What are the versions of mypy and Python you are using?

mypy==0.750+dev.8ada8e2cdb5432d41f188d2d0610ce21a2c62c12

Python 3.7.3

  • What are the mypy flags you are using? (For example --strict-optional)

mypy --strict

  • More Information

The call site looks good

unpack((1, 2, 3))  # no error
unpack((1, 2))  # no error
unpack((1, ))  # error as expected 

I also tried to replace the try-except with an if len(...) == 2 but that didn't change the error at all.

Currently, i use this workaround

def unpack(two_or_three: Union[Tuple[int, int], Tuple[int, int, int]]) -> None:
    one, two, *three = two_or_three
    ok = three[0] if three else None

But this is not ideal, because, the first version will actually throw a ValueError during runtime iif more than 4 elements are in the tuple.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions