I am using Python 3.11.5 with the below code:
import asyncio
from collections.abc import AsyncIterable
# Leave this iterable be, the question is about
# how to use many instances of this in parallel
async def iterable() -> AsyncIterable[int]:
yield 1
yield 2
yield 3
# How can one get multiple async iterables to work with asyncio.gather?
# In other words, since asyncio.gather works with asyncio.Task,
# (1) How can one convert an async iterable to a Task?
# (2) How can one use asyncio.gather to run many of these tasks in parallel,
# keeping the results 1-1 with the source iterables?
results_1, results_2, results_3 = asyncio.gather(iterable(), iterable(), iterable())
To restate the question, how can one get:
- An
AsyncIterableas anasynciotask, where the task iterates until exhaustion - Run multiple of these tasks in parallel, storing the results on a per-task basis
(e.g. for use with asyncio.gather)?
I am looking for a 1 - 3 line snippet showing how to connect these dots.
asyncio.gather'ing an async generator - what should this produce? You yield numbers, so it's not about async iterable producing new futures, right? Then what should happen - wait for first item? Consume this generator entirely asasync forwould do?async for item in iterable()to read the values from it sequentially. You put this async-for loop into an async function and run it in any convenient method (entrypoint -asyncio.run).asyncio.runmay be part of the answer. Thanks for asking for clarification!asynciofor your methods or generators. I suggest check this post out.