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?