<vetted />
Python
Mid-Level
Question 5 of 7

How do you write async code in Python?

Quick Answer

Use async/await with asyncio for I/O-bound tasks, run coroutines with asyncio.run, and use await for calling other async functions.

Detailed Answer8 paragraphs

Python's asyncio enables concurrent I/O-bound operations without threading complexity.

async def defines a coroutine—a function that can be paused and resumed. await pauses execution until the awaited coroutine completes, letting other coroutines run meanwhile. asyncio.run(main()) starts the event loop and runs your async entry point.

When to use async: I/O-bound work where you're waiting on network, files, or databases. Multiple operations can wait concurrently. For CPU-bound work, async doesn't help—use multiprocessing instead.

Concurrent execution with asyncio.gather runs multiple coroutines concurrently: results = await asyncio.gather(fetch_users(), fetch_posts()). Both requests happen simultaneously rather than sequentially.

asyncio.create_task schedules coroutines without immediately awaiting them. Useful for fire-and-forget operations or when you need more control over task management.

Async libraries: httpx or aiohttp for HTTP requests, asyncpg for PostgreSQL, redis.asyncio for Redis. Mixing sync and async code requires care—sync operations block the event loop.

Error handling works normally: try/except around await catches exceptions. asyncio.TaskGroup (Python 3.11+) provides structured concurrency with better error handling.

Don't overuse async. Sync code is simpler. Use async when you have many concurrent I/O operations—web servers handling many requests, scrapers fetching many pages, or clients making parallel API calls.

Key Takeaway

Use async/await with asyncio for I/O-bound tasks, run coroutines with asyncio.run, and use await for calling other async functions.

Ace your interview

Ready to Land Your Dream Job?

Join our network of elite AI-native engineers.