[Python] Typing a generic iterable

Discussão em 'Python' iniciado por Stack, Março 18, 2025.

  1. Stack

    Stack Membro Participativo

    I'm creating a function that yields chunks of an iterable.

    How can I properly type this function so that the return value bar is of type list[int].

    from typing import Any, Generator, Sequence

    def chunk[T: Any, S: Sequence[T]](sequence: S, size: int) -> Generator[S, None, None]:
    for i in range(0, len(sequence), size):
    yield sequence[i : i + size]

    foo: list[int] = [1,2,3]
    bar = chunk(foo, 1)


    Sequence[T] is invalid because TypeVar constraint type cannot be generic PylancereportGeneralTypeIssues

    Continue reading...

Compartilhe esta Página