1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Chunks of async_generator

Discussão em 'Python' iniciado por Stack, Novembro 26, 2025.

  1. Stack

    Stack Membro Participativo

    I can get chunks of an iterator doing as follow:

    def get_chunks_it(l, n):
    """ Chunks an iterator `l` in size `n`
    Args:
    l (Iterator[Any]): an iterator
    n (int): size of
    Returns:
    Generator[Any]
    """
    iterator = iter(l)
    for first in iterator:
    yield itertools.chain([first], itertools.islice(iterator, n - 1))


    Now let's say I have an asynchronous generator (python 3.6):

    async def generator():
    for i in range(0, 10):
    yield i
    await asyncio.sleep(1)


    How could I get chunks (let's say of size 3 that would yield [0, 1, 2], [3, 4, 5], [6, 7, 8], [9]) of the resulting async_generator so that I could write:

    async for chunk in get_chunk_it_async(generator(), 3):
    print(chunk)

    Continue reading...

Compartilhe esta Página