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

More Python tasks

Back to the full Python cheat sheet