`asyncio`
asyncio is the standard library for concurrent I/O on a single thread using an event loop, coroutines, and tasks. It overlaps waiting, not CPU-bound Python.
Detailed Explanation
A thread that blocks on socket.recv holds a whole OS thread while nothing happens. Asyncio runs many coroutines on one thread: when a coroutine awaits a socket, the loop starts another coroutine. Progress happens at await points. If you never await, you block the loop and everyone stalls.
async def defines a coroutine function. Calling it returns a coroutine object; it does not run the body. await runs it until the next await. asyncio.run(main()) is the usual entry: it creates a loop, runs main, and closes the loop. asyncio.create_task schedules a coroutine to run concurrently with the current one.
asyncio.gather waits for many awaitables. TaskGroup (3.11+) is the safer structured form: if one task fails, the others are cancelled and errors arrive as an ExceptionGroup. asyncio.timeout cancels a block that takes too long.
Only awaitable I/O belongs here: asyncio.sleep, streams, aiohttp, databases with async drivers. time.sleep, requests, and most ORM calls block the loop. Wrap them with asyncio.to_thread or run_in_executor if you must call them from async code.
Asyncio is not parallelism. One CPU-bound coroutine freezes the process. Move that work to a process pool. Asyncio is also not simpler than threads for two background jobs; it pays off when the number of sockets is large or when you want cancellation and timeouts as first-class operations.
Debugging is PYTHONASYNCIODEBUG=1, loop.slow_callback_duration, and remembering that a forgotten task is garbage-collected with a warning. Keep a reference to tasks you create, or use a TaskGroup.
Code Examples
import asyncio
async def fetch(name: str, delay: float) -> str:
await asyncio.sleep(delay) # stands in for network I/O
return name
async def main() -> None:
a, b = await asyncio.gather(fetch("db", 0.05), fetch("cache", 0.01))
print(a, b) # db cache (results keep gather order)
# asyncio.run(main())async def grouped() -> None:
async with asyncio.TaskGroup() as tg:
tg.create_task(fetch("a", 0.01))
tg.create_task(fetch("b", 0.01))Common Gotchas
Calling `async def` without `await`
you get a coroutine object and a "was never awaited" warning. The body did not run.
`time.sleep` or `requests` inside a coroutine
the loop freezes. Use async clients or `asyncio.to_thread`.
Fire-and-forget `create_task` without a reference
the task can be GC'd. Store it or use `TaskGroup`.
`gather` keeps result order, not finish order
use `as_completed` when you want first-done.