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

Can't determine the length of a Tuple from a Union type properly #9513

Closed
skytreader opened this issue Sep 30, 2020 · 2 comments
Closed

Can't determine the length of a Tuple from a Union type properly #9513

skytreader opened this issue Sep 30, 2020 · 2 comments
Labels
false-positive mypy gave an error on correct code feature

Comments

@skytreader
Copy link

skytreader commented Sep 30, 2020

Bug Report

For a Union type of two possible Tuple lengths, mypy reports index out of range for Tuples of the longer type even with a proper explicit check.

To Reproduce

from typing import Tuple, Union

SpamType = Union[
    Tuple[str, str, str],
    Tuple[str, str]
]

def egg(spam: SpamType) -> str:
    if len(spam) == 3:
        return spam[2]
    else:
        return spam[1]

print(egg(("a", "b")))
print(egg(("a", "b", "c")))

Expected Behavior

The code listing above should be perfectly typed.

Actual Behavior

mypy reports,

mypybug.py:10: error: Tuple index out of range
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used:
mypy==0.782
mypy-extensions==0.4.3
  • Mypy command-line flags: --ignore-missing-imports
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.7.0
  • Operating system and version: Ubuntu 16.04.7 LTS
@skytreader skytreader added the bug mypy got something wrong label Sep 30, 2020
@gvanrossum gvanrossum added false-positive mypy gave an error on correct code feature and removed bug mypy got something wrong labels Sep 30, 2020
@gvanrossum
Copy link
Member

Mypy only recognizes certain checks as runtime type checks -- this includes isinstance(x, C) and x is [not] None, but it does not include tuple length checks. So mypy doesn't narrow the union type to a specific union member based on the condition.

I suspect there's probably already another issue open that may have more discussion about this.

@gvanrossum
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
false-positive mypy gave an error on correct code feature
Projects
None yet
Development

No branches or pull requests

2 participants