Skip to content

Overly broad type inference when using zip(*x) to tranpose 2d iterable #13708

Open
@anabelle2001

Description

@anabelle2001

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.py1 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.

Footnotes

  1. https://github.com/python/typeshed/blob/494a5d1b98b3522173dd7e0f00f14a32be00456b/stdlib/builtins.pyi#L1813

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions