Skip to content

"Tuple index out of range" false positive despite "len() == 1" check #8733

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
dgrunwald opened this issue Apr 27, 2020 · 3 comments
Closed

Comments

@dgrunwald
Copy link

import typing 

def test(lookup: typing.Dict[str, typing.List[str]], key: str) -> None:
    vals = lookup.get(key, ())
    # reveal_type(vals) - Revealed type is 'Union[builtins.list[builtins.str], Tuple[]]'
    if len(vals) != 1:
        return
    # reveal_type(vals) - Revealed type is 'Union[builtins.list[builtins.str], Tuple[]]'
    print(vals[0]) # false positive: Tuple index out of range

I expect this code to be accepted by the type-checker without errors.
If len(vals) == 1, the Tuple[] case is impossible. The revealed type should change to just builtins.list[builtins.str] after the condition.

Mypy 0.770 already manages this with a if not vals: return check; it should also use len(tuple) <relop> integer-literal conditions to filter out tuple types that don't match the expected length.

@msullivan
Copy link
Collaborator

That's a plausible request for a type-narrowing feature that I'd review a pull request for if one was submitted

@abey79
Copy link

abey79 commented Jul 12, 2020

I ran into what I think is a similar issue today:

def demo(param: Union[Tuple[()], Tuple[int, int]]) -> Tuple[int, int]:
    if len(param) == 2:
        return param
    else:
        return 1, 1

Despite the len check, mypy doesn't recognise that the returned tuple is always of length 2 and yield this error:

 error: Incompatible return value type (got "Union[Tuple[], Tuple[int, int]]", expected "Tuple[int, int]")

@msullivan let me know if a new issue is warranted for this.

@ilevkivskyi
Copy link
Member

Duplicate of #1178

@ilevkivskyi ilevkivskyi marked this as a duplicate of #1178 Aug 3, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants