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

zip vararg #10651

Open
dfroger opened this issue May 20, 2022 · 2 comments
Open

zip vararg #10651

dfroger opened this issue May 20, 2022 · 2 comments

Comments

@dfroger
Copy link

dfroger commented May 20, 2022

mypy 0.950 (compiled: yes) and Python 3.10.4:

z1 = list(zip((1, 10), (2, 20), (3, 30)))  # correct: list[Tuple[int, int, int]]
z2 = list(zip(*[(1, 10), (2, 20), (3, 30)]))  # list[tuple[Any, ...]] but I expect list[tuple[int, int, int]]

Any chance to get mypy infer the type of zip(*l)?

Thanks for reading!

For the story it comes from here https://github.com/joelgrus/data-science-from-scratch/blob/d5d0f117f41b3ccab3b07f1ee1fa21cfcf69afa1/first-edition/code-python3/machine_learning.py#L18 !

@pranavrajpal
Copy link
Contributor

I think the problem with inferring the number of elements in each tuple is that mypy is that we don't track the length of lists in general.

In your simplified example we could determine the length of the list since it's a literal, but a fairly straightforward workaround is using a tuple instead:

z2 = list(zip(*[(1, 10), (2, 20), (3, 30)]))
reveal_type(z2) # N: Revealed type is "builtins.list[builtins.tuple[Any, ...]]"

z3 = list(zip(*((1, 10), (2, 20), (3, 30))))
reveal_type(z3) # N: Revealed type is "builtins.list[Tuple[builtins.int, builtins.int, builtins.int]]"

Supporting the general case well enough to support the code you linked would probably involve some form of https://peps.python.org/pep-0646/#shape-arithmetic to track the length of the input list across calls.

The revealed type including Any seems like a bug though. The inferred type should be list[tuple[int, ...]].

@hauntsaninja
Copy link
Collaborator

Pranav is correct. The remaining inference issue he mentions can be improved in typeshed, transferring the issue there.

@hauntsaninja hauntsaninja transferred this issue from python/mypy Sep 2, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
3 participants