[Python] asyncio.timeout for async generator does not work

Discussão em 'Python' iniciado por Stack, Setembro 14, 2024.

  1. Stack

    Stack Membro Participativo

    Why does asyncio.timeout not work when wrapping async generator like in example below?

    async def generate_many_numbers():
    for i in range(1000000000):
    yield i

    async def main2():
    async with asyncio.timeout(1):
    async for number in generate_many_numbers():
    print(number)

    asyncio.run(main2())


    Can it be the same issue which is described here? https://peps.python.org/pep-0789/

    I have noticed that adding async dummy sleep helps...

    async def generate_many_numbers():
    for i in range(1000000000):
    await asyncio.sleep(0)
    yield i

    async def iterate_through_numbers():
    async for number in generate_many_numbers():
    print(number)

    async def main2():
    async with asyncio.timeout(1):
    async for number in generate_many_numbers():
    print(number)

    async def main3():
    try:
    await asyncio.wait_for(iterate_through_numbers(), timeout=1)
    except asyncio.TimeoutError:
    print("The task timed out!")

    Continue reading...

Compartilhe esta Página