Async Python is ideal for I/O-bound operations — HTTP requests, databases, file I/O. One thread, thousands of concurrent operations.
Basics asyncio¶
import asyncio async def fetch_data(url: str) -> dict: async with aiohttp.ClientSession() as session: async with session.get(url) as response: return await response.json() async def main():
Async/Await in Python¶
urls = [“https://api.example.com/1”, “https://api.example.com/2”] results = await asyncio.gather(*[fetch_data(u) for u in urls]) return results asyncio.run(main())
When to Use async¶
- HTTP requests (aiohttp, httpx)
- Database queries (asyncpg, databases)
- File I/O
- WebSocket servers
- NOT for CPU-bound operations (use multiprocessing)
Key Takeaway¶
Async for I/O-bound, multiprocessing for CPU-bound. asyncio.gather for concurrent operations.