Skip to content

Tuple slice by variable results in incorrect type #7056

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
asottile opened this issue Jun 24, 2019 · 6 comments · Fixed by #7066
Closed

Tuple slice by variable results in incorrect type #7056

asottile opened this issue Jun 24, 2019 · 6 comments · Fixed by #7066
Assignees
Labels
bug mypy got something wrong priority-1-normal

Comments

@asottile
Copy link
Contributor

from typing import Tuple

sz = 2
x: Tuple[int, ...] = (1, 2)[:sz]
$ mypy --version
mypy 0.711
$ mypy t.py
mt.py:4: error: Incompatible types in assignment (expression has type "int", variable has type "Tuple[int, ...]")
@asottile
Copy link
Contributor Author

this is of course reduced from a larger program to a minimal reproduction

@emmatyping
Copy link
Member

emmatyping commented Jun 25, 2019

I checked and you can accomplish this with Literal and Final:

from typing import Tuple
from typing_extensions import Final

sz: Final = 2
x: Tuple[int, ...] = (1, 2)[:sz]

or if you prefer, a Literal[2] annotation should work as well for sz.

@asottile
Copy link
Contributor Author

in reality, sz is not a literal -- it's used in the following way:

ver = tuple(int(p) for p in x.split('.'))
sz = len(ver)
return min_ver[:sz] <= ver <= max_ver[:sz]

however this is lost when converting to a minimal testcase

Here's the current code with the # type: ignore -- this is definitely a bug and not a question, a slice of a tuple should never return a scalar

@emmatyping emmatyping added bug mypy got something wrong priority-1-normal and removed question labels Jun 25, 2019
@emmatyping
Copy link
Member

emmatyping commented Jun 25, 2019

Ah, you are correct, sorry I misunderstood the issue.

E: also it seems the same does not happen for lists, so this is a bug in tuple handling code.

@emmatyping emmatyping self-assigned this Jun 25, 2019
@emmatyping
Copy link
Member

It seems the changes in #3514 made the incorrect decision to return the union of elements when given a slice. I'm working on a fix.

JukkaL pushed a commit that referenced this issue Jun 27, 2019
This fixes #7056.

The idea is that we don't know what types a tuple slice will result in, 
other than a tuple of some sort.

For example, `(1,'', 3.3)[:a]` could result in `Tuple[()]`, `Tuple[int]`, 
`Tuple[int, str]`, or `Tuple[int, str, float]`.
@asottile
Copy link
Contributor Author

👏👏👏 awesome! thanks for the quick fix on this one 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong priority-1-normal
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants