Async/Await in Practice
Asyncio Core
Async/Await Crash Course
Coroutines let you write sequential-looking code that cooperatively multitasks.
Structure
import asyncio
async def fetch_order(order_id):
await asyncio.sleep(0.1)
return {'id': order_id}
async def main():
order = await fetch_order('123')
print(order)
asyncio.run(main())
asyncdeclares coroutines;awaitpauses until awaited tasks complete.- Use
asyncio.runto bootstrap top-level coroutines.
Gathering tasks
orders = await asyncio.gather(
fetch_order('123'),
fetch_order('456'),
fetch_order('789'),
return_exceptions=True,
)
asyncio.gatherwaits for all tasks; passreturn_exceptions=Trueto avoid cancellation.asyncio.create_taskschedules background work; keep references so you can await or cancel later.
Error handling
- Wrap awaits in try/except just like synchronous code.
- Use
asyncio.TimeoutErrorwithasyncio.wait_forto enforce deadlines. - Cancel tasks with
task.cancel()to clean up when shutting down.