🐍 Python Intermediate

What is Python asyncio?

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.