typestar

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

  1. gather schedules all three fetches at once.
  2. They overlap, so total time is the slowest, not the sum.
  3. Results come back in call order.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 4 in Async, step 25 of 53 in Pythonic Python.

← Previous Next →