Functions & Callablescritical

Coroutines & async/await

async def defines a coroutine. await suspends the coroutine until the awaited object completes, yielding control to the event loop.

Memory anchor

async/await = a chef juggling multiple dishes. 'await' means 'this is in the oven, let me chop veggies for another dish.' But if you stand and watch the oven (blocking call), every other dish burns.

Expected depth

Coroutines don't run until awaited or scheduled with asyncio.create_task(). await can only appear inside async def. async for and async with support asynchronous iteration and context management. asyncio.gather() runs multiple coroutines concurrently on the same event loop thread.

Deep — senior internals

Under the hood, async def compiles to a coroutine object (a specialized generator). await is equivalent to yield from for coroutine objects. The event loop drives all coroutines — it picks up suspended coroutines when their awaited I/O completes. asyncio.create_task() schedules a coroutine to run concurrently (not a new thread — still single-threaded). asyncio.run() creates a new event loop and runs the coroutine to completion. Python 3.11+ introduced task groups (async with asyncio.TaskGroup()) for structured concurrency.

🎤Interview-ready answer

async def defines a coroutine — a function that can suspend at await points and let the event loop run other coroutines. It's cooperative multitasking on a single thread. await doesn't block — it yields control until I/O completes. Use asyncio.create_task() to schedule coroutines concurrently. asyncio.gather() collects results. Key point: async code only helps if you await non-blocking coroutines — calling a blocking function without run_in_executor blocks the entire event loop.

Common trap

async def does not make code concurrent by itself. If you call time.sleep() instead of await asyncio.sleep(), or do CPU work, you block the entire event loop — no other coroutine runs during that time. Always use awaitable I/O or run_in_executor for blocking calls.

Related concepts