Skip to content

Narrow Union based on tuple fixed length check #9171

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
mthuurne opened this issue Jul 18, 2020 · 1 comment
Closed

Narrow Union based on tuple fixed length check #9171

mthuurne opened this issue Jul 18, 2020 · 1 comment

Comments

@mthuurne
Copy link
Contributor

When mypy 0.782 checks the following code:

from typing import Tuple, Union

def weird_cat(values: Union[Tuple[str, str], Tuple[str, str, str]]) -> str:
    if len(values) == 2:
        return values[0] + values[1]
    else:
        return values[0] + values[2] + values[1]

It reports:

testcase.py:7: error: Tuple index out of range  [misc]
            return values[0] + values[2] + values[1]
                               ^

There is no need to report an error here, since the tuple will always have a third element if the second return statement is reached.

I think mypy could filter the Union options using the len(values) == 2 guard, which is always true for Tuple[str, str] and always false for Tuple[str, str, str].

The example in this comment from @abey79 looks equivalent to this issue, but the test case for #8733 itself also includes a List, so it has to deal with runtime length rather than the static length of a tuple type.

@ilevkivskyi
Copy link
Member

Duplicate of #1178

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