Skip to content

Cannot unpack Union of Tuples of different lengths #7965

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
nielsbuwen opened this issue Nov 18, 2019 · 1 comment
Closed

Cannot unpack Union of Tuples of different lengths #7965

nielsbuwen opened this issue Nov 18, 2019 · 1 comment

Comments

@nielsbuwen
Copy link

  • 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.

@JukkaL
Copy link
Collaborator

JukkaL commented Nov 18, 2019

Unfortunately, the first example is too difficult for mypy to figure out. For example, mypy would have to understand that a mismatch in tuple lengths results in ValueError, but mypy doesn't have any knowledge of which exceptions may be raised by various operations.

However, a if len(...) == x check to narrow narrow down the union would be feasible (tracked in #1178).

@JukkaL JukkaL closed this as completed Nov 18, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants