AsyncIO lets a single thread juggle many I/O-bound tasks concurrently. Instead of blocking while waiting for a network response, an await yields control so other work can run in the meantime. It's how Python handles thousands of simultaneous connections efficiently.
Coroutines: async and await
async def defines a coroutine; await pauses it while waiting, freeing the event loop to run other coroutines:
import asyncioasync def fetch(n):await asyncio.sleep(1) # simulate a network call (non-blocking)return n * 2async def main():result = await fetch(1) # await a single coroutineprint(result)asyncio.run(main()) # start the event loop
Running many at once
asyncio.gather runs coroutines concurrently — three 1-second waits finish in ~1 second, not 3:
async def main():results = await asyncio.gather(fetch(1), fetch(2), fetch(3))print(results) # [2, 4, 6] — after ~1s total, not 3s
When to use it
Key takeaways
- 01async def defines a coroutine; await pauses it while waiting, freeing the event loop.
- 02asyncio.run starts the loop; asyncio.gather runs coroutines concurrently.
- 03Concurrent awaits overlap their waiting — many I/O tasks in the time of one.
- 04Best for I/O-bound work (network, disk, DB).
- 05Not a speed-up for CPU-bound work — use multiprocessing there.
