asyncio.gather in Python
Running many coroutines concurrently and collecting results.
import asyncio
async def fetch(name, delay):
await asyncio.sleep(delay)
return f"{name}: done"
async def main():
results = await asyncio.gather(
fetch("users", 0.3),
fetch("posts", 0.2),
fetch("stats", 0.1),
)
return results # all three ran concurrently
answers = asyncio.run(main())
How it works
gatherschedules all three fetches at once.- They overlap, so total time is the slowest, not the sum.
- Results come back in call order.
Keywords and builtins used here
asyncawaitdeffetchmainreturn
The run, in numbers
- Lines
- 18
- Characters to type
- 290
- Tokens
- 80
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 46 seconds.
Step 2 of 4 in Async, step 25 of 53 in Pythonic Python.