Skip to content
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

Tuple index out of range doesn't take into account len check when accessing Union of Tuples of varying lengths #13941

Closed
posita opened this issue Oct 24, 2022 · 2 comments
Labels
feature topic-type-narrowing Conditional type narrowing / binder

Comments

@posita
Copy link
Contributor

posita commented Oct 24, 2022

Where a type is a Union of Tuples of varying lengths, Mypy remains blissfully unaware of any len validation before accessing elements beyond the minimum length.

# test_case.py
from typing import Optional, Tuple, Union

def get_third_thing_works_correctly(thing: Tuple[int, int, Optional[int]]):
    return thing[2]

def get_third_thing_errors_correctly(thing: Tuple[int, int]):
    return thing[2]  # <-- correctly results in "Tuple index out of range [misc]"

def get_third_thing_false_positive(
    thing: Union[Tuple[int, int], Tuple[int, int, Optional[int]]]
):
    if len(thing) >= 3:
        return thing[2]  # <-- false positive
    else:
        return None

Results:

% python --version
Python 3.10.6
% mypy --version
mypy 0.982 (compiled: yes)
% mypy --config=/dev/null test_case.py
/dev/null: No [mypy] section in config file
test_case.py:8: error: Tuple index out of range
test_case.py:14: error: Tuple index out of range
Found 2 errors in 1 file (checked 1 source file)
@posita posita added the bug mypy got something wrong label Oct 24, 2022
@JelleZijlstra JelleZijlstra added topic-type-narrowing Conditional type narrowing / binder feature and removed bug mypy got something wrong labels Oct 24, 2022
@AlexWaygood
Copy link
Member

This is arguably a duplicate of #1178, though it's a slightly different sympton of the same problem

@JelleZijlstra
Copy link
Member

It's the same thing: a feature request that we use len() for type narrowing. Closing as a duplicate.

@JelleZijlstra JelleZijlstra closed this as not planned Won't fix, can't repro, duplicate, stale Oct 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature topic-type-narrowing Conditional type narrowing / binder
Projects
None yet
Development

No branches or pull requests

3 participants