How do async and await work in Python, and when do you reach for asyncio?
async def defines a coroutine function, and calling that function does not run its body. It creates a coroutine object that has to be driven by an event loop. The await inside the body is a place where the coroutine can stop. When the coroutine reaches an await, it hands control back to the loop, the loop runs other ready tasks in the meantime, and the coroutine continues later when the operation it was waiting for has finished. The earlier questions in this topic looked at threads and processes, and this answer shows the third tool that Python gives you for doing several things at once.
The event loop is the part that makes it work. It keeps one set of tasks that are ready to run and another set of callbacks that are waiting for input or output. When a task waits for a socket to become readable, the loop registers its interest in that socket and moves on to the next ready task. When the socket really does become readable, the task is scheduled again. Thousands of tasks can be in flight inside a single thread this way, because a task is cheap. A task is only a coroutine plus its own state, while a thread needs its own stack.
So when do you reach for asyncio? You reach for it when you have a lot of concurrent input and output and you would rather use one thread than hundreds of them. An async web server that holds thousands of open connections, a script that fetches many addresses at once, or a client that talks to several services in parallel are the classic cases. The rule of thumb is that asyncio gives you concurrency and not parallelism. It overlaps the waiting, and it does not make the computing any faster.
Two practical points are worth having ready for an interview. Never call a blocking function inside a coroutine, because that blocks the whole event loop for everybody. Use an async version of the function, or push the blocking work into a thread with asyncio.to_thread. And asyncio.gather lets you await several coroutines at once, which is usually the reason you reached for asyncio in the first place.