Concurrency with async and await
3.15.2
Use coroutines, schedule independent I/O tasks, and handle cancellation.
On this page
Coroutines and the event loop
Calling an async def function creates a coroutine object. await waits for an awaitable and can suspend the current task so other tasks can run. Use asyncio.run() as a normal script entry point. A notebook with an active event loop can typically use top-level await.
import asyncio
async def main():
await asyncio.sleep(0)
print("Ready")
asyncio.run(main())
Example output
Ready
Run independent tasks together
TaskGroup schedules coroutines and waits for the group before leaving its block. A task failure generally cancels its sibling tasks. Prefer asynchronous I/O inside the event loop and keep CPU-heavy or blocking work away from it. Use try/finally for cleanup and let cancellation propagate.
import asyncio
async def read_source(name):
await asyncio.sleep(0.01)
return name
async def main():
async with asyncio.TaskGroup() as group:
sales = group.create_task(read_source("sales"))
inventory = group.create_task(read_source("inventory"))
print(sales.result(), inventory.result())
asyncio.run(main())
Example output
sales inventory