🐍 Python Intermediate

What is Python asyncio?

Why Interviewers Ask This

This question targets practical, hands-on experience with Python. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.

Answer

asyncio is Python's built-in library for writing single-threaded concurrent code using coroutines and an event loop. Define a coroutine with async def: async def fetch(url): response = await aiohttp.get(url); return await response.text(). await suspends the coroutine until the awaited operation completes, allowing other coroutines to run. Run: asyncio.run(main()). Run multiple coroutines concurrently: results = await asyncio.gather(fetch(url1), fetch(url2), fetch(url3)). asyncio is ideal for I/O-bound code with many concurrent operations (HTTP clients, WebSocket servers, database connections). Unlike threads, coroutines have no context-switching overhead. Key packages: aiohttp (async HTTP), asyncpg (async PostgreSQL), aiomysql. FastAPI and Starlette are async Python web frameworks. asyncio is NOT parallel — it is concurrent single-threaded.

Pro Tip

This topic has Python-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.