Lesson · Async Python
Coroutines & async / await
75 min readCoroutines & async / await
`async` functions create coroutines that cooperate by suspending at `await`. Asyncio is primarily a concurrency model for many overlapping I/O operations, not a magic way to make CPU work parallel.
Learning goals
- Distinguish an
async deffunction from the coroutine object you get when you call it. - Trace control moving between
main,fetch, and the event loop at eachawait asyncio.sleep(...). - Explain why awaiting two calls in sequence takes the sum of their delays while
asyncio.gatheroverlaps them. - Read a "coroutine was never awaited" warning and repair the call that produced it.
- Identify the suspension point that makes concurrency possible and the blocking calls that destroy it.
Mental model
A coroutine function is the recipe; calling it produces a coroutine object that has not started, and only await hands that object to the loop and lets it run. Nothing in the body executes at call time, which is why an unawaited call prints nothing and finishes with a warning.
Mental model
read it top to bottom
async def fetch(...) definition only, no body runs ↓ call it <coroutine object fetch> suspended before the first line ↓ await it runs to each await suspension point: the loop runs other work ↓ finishes return value or exception delivered back to the awaiting line
Core idea
An async def function does not run when you call it: the call builds a coroutine object, and await is what drives that object to completion. Since the loop can only run other work at a suspension point, concurrency comes from awaiting operations that actually wait, such as asyncio.sleep, not from the async keyword itself.
Coroutine functions
A coroutine function is declared with async def and returns a coroutine object when called, without executing the body. It remains a regular function object otherwise: inspect.iscoroutinefunction recognizes it, and only awaiting or scheduling the returned object runs the code inside.
Coroutine objects
A coroutine object is the suspended computation returned by calling a coroutine function. It advances only while something awaits or schedules it, and it is single use: awaiting the same object twice raises RuntimeError, while creating one and discarding it triggers a RuntimeWarning about a coroutine that was never awaited.
await
await suspends the current coroutine until an awaitable makes progress or completes. Suspension gives the event loop a chance to run other tasks.
Cooperative scheduling
Asyncio tasks switch at explicit suspension points rather than being preempted at arbitrary Python instructions. A coroutine that performs long blocking work without awaiting can stall the whole loop.
Suspension points
A suspension point is an await that yields control back to the event loop, such as await asyncio.sleep(0) or a wait on I/O. Only there can other tasks run, so a coroutine that keeps computing without awaiting monopolizes the loop even though its definition is async.
Walkthrough
async def fetch(name, delay)defines a coroutine function; the callfetch("A", 0.1)inmainbuilds a coroutine object whose body has not started yet.await asyncio.sleep(delay)is the suspension point: it registers a timer and returns control to the loop, and the loop resumesfetchabout 0.1 seconds later to runprint("done", name).- The first
printruns when the coroutine is first awaited, andreturn namesets the value that lands inresult, which the finalprintthen shows. - Predict before running: the three printed lines in order, and what changes in timing and output when
asyncio.sleep(delay)is replaced bytime.sleep(delay).
Experiments to try
- Delete the
awaitin front offetch("A", 0.1)and run again: read theRuntimeWarning: coroutine 'fetch' was never awaited, then repair the line and confirm the output returns. - Swap
asyncio.sleep(delay)fortime.sleep(delay)and time both versions withtime.perf_counter(); decide which one returns control to the loop during the wait. - Change
maintoawait asyncio.gather(fetch("A", 0.2), fetch("B", 0.1))and write down the interleaved start/done lines; explain the order from the two delays. - Await the same coroutine twice (
coro = fetch("A", 0); await coro; await coro) and read theRuntimeErrorthat explains coroutine objects are single use.
Common mistakes
- Calling a coroutine function and expecting it to run: with no
awaitor task, the body never executes, and Python reports only aRuntimeWarningabout the unawaited coroutine, so the visible symptom is silence. - Using
time.sleepinside a coroutine: it holds the thread for the whole delay, so the loop cannot resume any other task and the function behaves like a slower synchronous call. - Reading
awaitas "start this in the background":await fetch(...)waits for completion, and overlapping calls require scheduling them first withasyncio.create_taskorasyncio.gather. - Awaiting values that are not awaitable, such as the result of a plain function call: the
awaitexpression raisesTypeErrorinstead of running anything.
Practice: Easy
- Run the worked example and timestamp every print with
time.perf_counter(); confirm "done A" lands about 0.1 seconds after "start A" and that the program is sequential. - Remove the
awaitinmainand quote the exact warning the interpreter prints; then fix the call two ways, withawaitand withasyncio.create_task. - Await
fetch("B", 0.05)instead of the "A" call and list which lines changed and which stayed identical.
Practice: Medium
- Rewrite
mainaroundasyncio.gather(fetch("A", 0.2), fetch("B", 0.1))and annotate each printed line with the task and the delay that produced it. - Wrap one
fetchcall inasyncio.create_task(...), await the handle, and compare the timing of the gathered and sequential versions; state what the task adds. - Replace
asyncio.sleep(delay)with a busy computation such assum(range(10**7))and predict, then measure, what happens to the other task on the loop.
Practice: Hard
- Write
fetch_many(names, delay)that gathers onefetchper name and returns results in input order; test it with delays reversed and assert the order holds. - Build a comparison setup with three variants of
main(sequential awaits,create_taskplusgather, and onetime.sleepinside an otherwise async flow) and explain each run from cooperative scheduling. - Add a cancellation path: start
fetch("C", 10)as a task, cancel it after 0.05 seconds, and record whereCancelledErrorsurfaces and whetherprint("done", ...)ever runs.
Lesson checklist
- I can say what
fetch("A", 0.1)alone creates and whatawaitadds to it. - I can point to the suspension point in the worked example and explain what the loop does during it.
- I can predict the print order of
gather(fetch("A", 0.2), fetch("B", 0.1))from the delays. - I can recognize an unawaited coroutine warning and repair the call that caused it.
Remember
Calling an `async def` function produces a coroutine object, and only `await` runs it, suspending at each wait point so the loop can do other work. The `async` keyword alone adds no concurrency: overlapping I/O needs awaits that actually yield, and task scheduling builds on that fact in the next lessons.
Interview angles
What is the main purpose of **Coroutine functions**?+
A coroutine function is declared with async def and returns a coroutine object when called, without executing the body. It remains a regular function object otherwise: inspect.iscoroutinefunction recognizes it, and only awaiting or scheduling the returned object runs the code inside.
What should you pay attention to when using **Coroutine objects**?+
A coroutine object is the suspended computation returned by calling a coroutine function. It advances only while something awaits or schedules it, and it is single use: awaiting the same object twice raises RuntimeError, while creating one and discarding it triggers a RuntimeWarning about a coroutine that was never awaited.
How does **await** fit into this lesson?+
await suspends the current coroutine until an awaitable makes progress or completes. Suspension gives the event loop a chance to run other tasks.
What happens when a coroutine object is created but never awaited?+
The body never runs. When the abandoned object is garbage collected, the interpreter emits a RuntimeWarning that the coroutine was never awaited, so a missing await shows up as silence plus a warning rather than an exception.