Overly broad type inference when using zip(*x) to tranpose 2d iterable
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 5.1k
- Forks
- 2.1k
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 82
Description
Description:
When transposing a 2d iterable x: Iterable[Iterable[T]] using zip(*x), I've noticed typeshed's type annotations result in the return type being inferred as zip[tuple[Any, ...]] rather than the expected zip[tuple[T, ...]]. It would be nice if builtins.py^1 had an overload for this use case.
Expected behavior
When x has type Iterable[Iterable[T]], the expression zip(*x) should be inferred as zip[tuple[T, ...]], preserving the element type information through the transpose operation.
Actual behavior
The expression zip(*x) is inferred as zip[tuple[Any, ...]].
Possible solution
Add the following overloads to zip:
Pre 3.10:
@overload
def __new__(
cls,
*iterables: Iterable[_T1],
) -> zip[tuple[_T1, ...]]: ...
3.10 or later:
@overload
def __new__(
cls,
*iterables: Iterable[_T1],
*,
strict: bool = ...
) -> zip[tuple[_T1, ...]]: ...
While I have seen zip(*x) in the wild, I have not seen zip(a,b,c,*x) in any environment before, so I don't think it's necessary to write an overload for that edge case.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Open stdlib/builtins.pyi at the linked zip definition and compare the existing overloads with the proposed pre-3.10 and 3.10+ signatures. Confirm that zip(*x) for Iterable[Iterable[T]] is inferred as zip[tuple[T, ...]] rather than zip[tuple[Any, ...]], while preserving strict handling.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 58/100