Async & Await in Python
From the Python cheat sheet ยท Advanced Features ยท verified Jul 2026
Async & Await
Cooperative concurrency for I/O-bound work (network, files, DBs).
python
import asyncio
# Define an async function (coroutine)
async def fetch_user(user_id: int) -> dict:
await asyncio.sleep(1) # Simulate network call
return {"id": user_id, "name": "Alice"}
# Run an async function from sync code
async def main():
user = await fetch_user(1)
print(user)
asyncio.run(main())
# Run many concurrently
async def fetch_all():
results = await asyncio.gather(
fetch_user(1),
fetch_user(2),
fetch_user(3),
)
return results๐ก Async is for I/O-bound work (network, files, DBs) โ not CPU-bound work
โก asyncio.gather() runs coroutines concurrently; await runs them one at a time
๐ Never call a coroutine without await โ you get a warning, not a result
๐ข Use asyncio.to_thread() to run a blocking sync function without blocking the loop