L6Β·Expert

⚑async / await & Event Loop

Cooperative concurrency for I/O-bound work.

asyncawaitasynciocoroutine

Β§ 1Coroutines

async def creates a coroutine function. Calling it returns a coroutine object β€” nothing runs until you await or schedule it.

Β§ 2Event loop

asyncio.run(main()) starts a loop. Await points let other tasks progress while you wait on I/O.

Β§ 3Gather

asyncio.gather(*coros) runs them concurrently and returns results in order.

Example

1import asyncio​
2​
3async def fetch(name, delay):​
4 await asyncio.sleep(delay)​
5 return f"{name} done"​
6​
7async def main():​
8 results = await asyncio.gather(​
9 fetch("A", 0.3),​
10 fetch("B", 0.1),​
11 fetch("C", 0.2),​
12 )​
13 print(results)​
14​
15asyncio.run(main())​

Try it live Β· Python runs in your browser

Loading playground…

Checkpoint quiz

Question 1 / 2
Is async/await good for CPU-bound work?