Skip to content

Wrong type inference with unpacking and enumerate() #7434

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
JelleZijlstra opened this issue Aug 30, 2019 · 3 comments
Closed

Wrong type inference with unpacking and enumerate() #7434

JelleZijlstra opened this issue Aug 30, 2019 · 3 comments
Labels
bug mypy got something wrong priority-1-normal

Comments

@JelleZijlstra
Copy link
Member

JelleZijlstra commented Aug 30, 2019

Mypy infers that the type of [*enumerate(["x", "y"])] is List[str], when it should be List[Tuple[int, str]].

A repro is below, with a slightly simplified copy of the typeshed definition of enumerate. Note that type inference is right if I define enumerate() as a function instead of a class.

$ python -m mypy tmp/enumunpack.py 
tmp/enumunpack.py:14: note: Revealed type is 'builtins.list[builtins.str*]'
tmp/enumunpack.py:21: note: Revealed type is 'builtins.list[Tuple[builtins.int, builtins.str*]]'
$ cat tmp/enumunpack.py 
from typing import Iterable, Iterator, Tuple, TypeVar, Generic

_T = TypeVar("_T")


class enumerate(Iterable[Tuple[int, _T]], Generic[_T]):
    def __init__(self, iterable: Iterable[_T], start: int = ...) -> None:
        ...

    def __iter__(self) -> Iterator[Tuple[int, _T]]:
        ...


reveal_type([*enumerate(["x", "y"])])


def enumerate_fn(iterable: Iterable[_T]) -> Iterator[Tuple[int, _T]]:
    ...


reveal_type([*enumerate_fn(["x", "y"])])

I tried this on master and on 0.730.

@JukkaL JukkaL added bug mypy got something wrong priority-1-normal labels Sep 2, 2019
@JukkaL
Copy link
Collaborator

JukkaL commented Sep 2, 2019

This seems to happen only in certain contexts. I wonder if we are missing a map_instance_to_supertype call somewhere. In particular, for x, y in enumerate(...) seems to work.

@AlexWaygood
Copy link
Member

@JelleZijlstra
Copy link
Member Author

Great!

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

No branches or pull requests

3 participants