A coroutine is the same suspended frame as in the previous lesson, and await is a direct descendant of yield from. From this you can derive why one synchronous call takes the whole service down, why a task must be held by a reference, and how TaskGroup differs from gather.
Commit to an output and a reason before you open the answer.
async def co():
print("body started")
return 1
c = co()
print("created:", c)created: <coroutine object co at 0x...>Plus the warning “coroutine was never awaited”. The body did not run.async def slow(n):
await asyncio.sleep(0.01)
return n
# 50 tasks through gather
# versus 50 tasks one after another through awaitgather: 0.011 s
sequentially: 0.509 sThe difference is exactly the number of tasks. And there is one thread.async def main():
async with asyncio.TaskGroup() as tg:
tg.create_task(long()) # sleeps for a second
tg.create_task(boom()) # fails at oncelong cancelled
TaskGroup: caught (ValueError('bam'),)The neighbouring task did not run to the end — it was cancelled.async def worker(): ...
async def main():
asyncio.create_task(worker()) # the reference was not kept
await asyncio.sleep(10)From lesson 13 we know: a generator is an object with a suspended frame, and yield from builds a channel all the way through. Async is a layer on top of exactly that.
A coroutine is an object with a suspended frame, like a generator. Since 3.5 it is a separate type, but the machinery is the same.
await passes control up the chain — to whoever started that chain. It is yield from under another name and with its own protocol.
The event loop is an ordinary loop in one thread. It takes a ready task, resumes its frame, runs until the nearest await that cannot answer immediately, takes control back and picks the next one.
Snippet A is the same as consequence 2 of lesson 13. co() creates an object; the body does not run. You need an await, or asyncio.run, or wrapping it in a task.
Hence the most common beginner's mistake — a forgotten await: the code does not fail, it simply does nothing, and at the end a warning about an unexpected coroutine is printed. And hence also the fact that a coroutine can be created in one place and started in another.
Snippet B. Fifty tasks of ten milliseconds each complete in forty-six milliseconds instead of five hundred. But there is no parallelism here: while one task waits, the loop attends to others. All this time one thread was working.
So the gain arises exactly where there is waiting — the network, the disk, a database's reply. On computation there is none at all: a hundred coroutines computing hashes will take exactly the sum of their times, and the event loop will not help in any way.
This is the main practical conclusion of the lesson, and it follows from consequence 2 in one line. Control returns to the loop only at an await. A synchronous call that waits for a second holds control for the whole second — and for that time the whole service serves nobody.
And outwardly nothing is broken: no errors, the task completes, it is just that under load latency grows inexplicably. One requests.get inside a coroutine cancels the point of all the async in the process.
Hence a rule with no exceptions: inside a coroutine every blocking operation must go into a pool through run_in_executor or have an async counterpart. And the same question must be put to libraries: the database driver, the HTTP client, file handling — synchronous versions inside the event loop are unacceptable.
Snippet D. create_task schedules a coroutine and returns a task object. The event loop holds a weak reference to it, so as not to stand in the way of collection — that is, by the rules of lesson 09, a task can be collected before it finishes if nobody holds it.
It shows up as “a task sometimes did not finish” under load — and that is the worst kind of bug: it reproduces rarely and depends on when the collector happens to run. The cure follows from the mechanism: put the tasks into a set and remove them on completion, or use TaskGroup, which holds them itself.
Snippet C. On an exception in any task, TaskGroup cancels the others and on exit guarantees that nothing is left running. Errors arrive as a group and are caught through except* (lesson 12).
gather by default behaves differently: it hands back the first exception, while the neighbouring tasks go on running in the background — with their results and their possible errors, which nobody will ever learn about. This is “structured concurrency” versus its absence: with TaskGroup the scope of the block coincides with the lifetime of the tasks.
Cancellation is an exception, not a kill. CancelledError is raised inside the task at the point of await. So a task can intercept it and not be cancelled; so except Exception will not catch it (since 3.8 it inherits from BaseException) — whereas except BaseException will catch it and break cancellation.
The event loop does not preempt. A coroutine that went into an infinite loop with no await will not be interrupted by anything: the scheduler is cooperative, not preemptive. A fundamental difference from threads.
Async does not cancel the GIL; it works around a different problem. It is about waiting, not computation. Compute-bound load needs processes or an extension that releases the GIL — that is R3 and R6, not R5.
Root R5: a suspended frame with a two-way channel. Python's async is not a separate subsystem but the application of the traversal mechanism to another task.
The chronology confirms this literally. In 2005 yield became two-way (PEP 342) — and libraries appeared that wrote concurrency on bare generators. In 2012 yield from was added (PEP 380) — and chains began to be built all the way through. In 2014 asyncio grew on top of this, where a coroutine was literally a generator with a decorator. And only in 2015 (PEP 492) did the words async and await appear — as separate syntax for something that already worked.
So the knowledge of lesson 13 here is not “useful context” but literally the mechanism: if you understand the suspended frame and the yield from channel, you already understand await.
The most precise analogy is C++20 coroutines, as in the previous lesson: co_await and await do the same thing, suspending the frame and handing control to the caller. If you keep this in mind, all of asyncio splits into two parts: a language primitive (a frame plus suspension) and an ordinary library on top of it (a queue of ready tasks, a selector on epoll, timers). There is nothing magical in the second part — it is a loop you could write yourself in an evening.
The second useful image is cooperative multitasking in old systems: a task decides for itself when to give up control. Windows 3.x and Mac OS before X worked this way, and suffered from exactly the same thing — one hung program froze everything. Consequence 3 is exactly that disease, and it is fundamental to the model, not a defect of the implementation.
Questions that come up on their own if you read closely. The answer is under the question.
await?Because then the one guarantee asyncio exists for would disappear.
await is not decoration but a marker of a switch point. As long as there is none, code runs without preemption: nobody can cut in between two awaits. That is something threads do not have, and it is exactly why asyncio needs no locks for “read-modify-write”.
counter = 0
async def bump():
global counter
tmp = counter # between these lines
tmp += 1 # there will be no switch —
counter = tmp # there is not a single await
With implicit async every line would become a potential switch point, and we would get all the same races as with threads — only without timer preemption, that is, non-deterministic and impossible to reproduce.
Second: await is documentation. Reading a function, you see every place where control can leave. A review of “where could another request cut in here” comes down to searching for a word in the text.
The price of the decision is known as “function colouring”: an async function cannot be called from a synchronous one, and async spreads up the stack all the way to the entry point. Go chose the opposite — goroutines and implicit switching — and paid with needing mutexes and a race detector. It is a trade, not a victory of one side.
Because it does not add executors; it only waits more efficiently.
The event loop is one thread. It can hold ten thousand open sockets, because waiting needs no processor: a task is taken off execution at an await and comes back when the data has arrived. But if a task computes, it goes nowhere and holds the whole loop.
import asyncio, time
async def cpu(n):
t = 0
for i in range(n): t += i # not a single await
return t
async def main():
t0 = time.perf_counter()
await asyncio.gather(cpu(5_000_000), cpu(5_000_000))
print(f"{time.perf_counter() - t0:.2f} s") # exactly the sum, no faster
asyncio.run(main())
And worse: one synchronous call poisons the whole process. An ordinary requests.get inside a handler blocks the loop entirely — all other connections freeze for the duration of the request. This is the most common accident in async services, and a profiler shows it poorly: the time hangs in one place, and everyone suffers.
The rule. Waiting — asyncio. Computing in Python — processes (lesson 20). Computing in a C extension — threads, because the GIL is released there (lesson 15). A mixed load — loop.run_in_executor for the heavy pieces, so that they go off to a separate thread or process and do not hold the loop.
TaskGroup or gather — why was a new mechanism needed?Because gather cannot properly cancel its neighbours on an error — and leaves tasks dangling.
The problem with gather: if one task fails, the others keep working. The exception surfaces upward, while the background coroutines stay alive — with open connections, half-written files and a later “Task exception was never retrieved” in the log.
import asyncio
async def boom(): raise ValueError("bam")
async def long():
try:
await asyncio.sleep(10)
except asyncio.CancelledError:
print("long cancelled"); raise
async def main():
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(long())
tg.create_task(boom())
except* ValueError as eg:
print("TaskGroup: caught", eg.exceptions)
asyncio.run(main())
# → long cancelled
# → TaskGroup: caught (ValueError('bam'),)
TaskGroup (3.11) gives structured concurrency: the block will not complete until all the tasks have completed; on an error in one, the rest are cancelled; all errors are collected into an ExceptionGroup and caught through except*.
When gather after all: when you need the results of all tasks, including the failed ones — gather(..., return_exceptions=True). For example, polling ten replicas where two may be unavailable, and that is fine.
In all other cases TaskGroup is the right default choice, and it is a direct transfer of ideas from Trio, which proved so much more convincing that they were pulled into the standard library.
await is a direct descendant of yield from: all of async grew out of the traversal protocol and appeared as syntax for something that already worked on generators. Calling a coroutine executes nothing; you need an await or a launch. The event loop is an ordinary loop in one thread: the gain arises where there is waiting and is completely absent on computation. Hence the main practical consequence — control returns to the loop only at an await, so one synchronous call stops the whole service, and outwardly nothing is broken, latency just grows. A task created through create_task must be held by a reference: the loop holds only a weak one, and by the rules of lesson 09 the task can vanish before it finishes. And TaskGroup differs from gather not in convenience but in a guarantee: on an error it cancels the neighbours and leaves nothing running after the block is exited.C++20 gave exactly the same primitive — a suspended frame with co_await — but gave neither a scheduler nor an event loop: people write them themselves or take them from a library. Python ships the batteries included, C++ leaves the choice. Hence in C++ the frame can be placed so that the compiler eliminates it altogether, while in Python the frame is always on the heap.
Go solved the task in a fundamentally different way: a goroutine is not a frame on the heap but a lightweight thread with its own stack, and the scheduler is preemptive. So a compute loop in a goroutine will not block the others — whereas a coroutine in Python will. Plus goroutines really are spread across cores. The price is a considerably more complex runtime, and function colour still surfaces through channels.
JavaScript is the closest: one thread, an event loop, async/await on top of promises. And the same disease — heavy synchronous code blocks everything. The difference is that in the browser there was never an alternative, and the whole ecosystem has been asynchronous from birth; Python got async twenty years after it started, and the synchronous libraries did not go anywhere.
Hence the “function colour problem”, which Go does not have: in Python a function is either synchronous or asynchronous, and they cannot be mixed without explicit bridges.
An async handler in which one library turned out to be synchronous. Finding it from the logs is next to impossible.
async def handle(request):
user = await db.fetch_user(request.user_id) # asynchronous, good
profile = requests.get(PROFILE_URL, timeout=2) # ← synchronous
return render(user, profile.json())
The line looks innocent: the timeout is set, errors are handled. But requests.get does not give control back to the event loop — it holds the thread until the response. While it waits, not a single other request is served.
Under load it looks like this: the average latency is acceptable, p99 is catastrophic, CPU usage is low, and all of it without a single error in the logs. The profiler shows the time spent waiting — that is, exactly in what was supposed to be free.
Review lets it through because the mixing is visible only if you know which libraries are asynchronous. That is exactly why the function colour problem exists: async def in the signature is a promise the language does not check.
async def handler():
async with httpx.AsyncClient() as client: # the async counterpart
profile = await client.get(PROFILE_URL, timeout=2)
async def handler_fallback(): # if there is no counterpart
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, requests.get, PROFILE_URL)
How to find the existing ones: asyncio.run(..., debug=True) or loop.slow_callback_duration — the loop itself logs a warning if a callback ran longer than the threshold. It is the cheapest way to catch consequence 3 in someone else's code.
TaskGroup — 0.011 s, in one threadA loop with an await inside looks asynchronous and is not.
async def sequential(urls):
results = []
for url in urls:
results.append(await fetch(url)) # wait for each one in turn
return results
async def concurrent(urls):
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(fetch(url)) for url in urls]
return [t.result() for t in tasks]
| 50 operations of 10 ms | time |
|---|---|
sequentially through await | 0.509 s |
| concurrently | 0.011 s |
A forty-six-fold gain, and still one thread. The first variant does not use the mechanism at all: an await in a loop means “wait for this one, then get on with the next”, while the whole point is for the waits to overlap.
Why TaskGroup and not gather. Consequence 5: on an error in one task the group will cancel the rest and leave nothing running after the block is exited. With gather the neighbours carry on in the background and their exceptions are lost. Plus the group holds references to the tasks itself — consequence 4 is closed for free.
Limiting concurrency. Fifty simultaneous requests to someone else's API are a way to get banned. A semaphore solves this in two lines and does not break the gain:
sem = asyncio.Semaphore(10)
async def fetch_limited(url):
async with sem:
return await fetch(url)
Run the four snippets and check them against your prediction. Then:
async def t():
try: await asyncio.sleep(10)
except asyncio.CancelledError: print("being cancelled"); raise
# create a task, cancel it after 0.1 s
# What happens if you remove raise? And if you put except Exception?
asyncio.run(asyncio.run(main()))
# Why can it not be nested? What does the error say?
async def spin():
s = 0
for i in range(10**8): s += i # not a single await
return s
# Run it together with another task. What will happen to that one?
asyncio.run(main(), debug=True)
# What appears in the output if there is a synchronous call inside?
The third question is direct confirmation that the scheduler is cooperative: the neighbouring task will not get control a single time until the loop finishes.
Lib/asyncio/base_events.py, the _run_once method. The heart of the whole library, and it fits on one screen: compute the nearest timer, call the selector with that timeout, distribute the ready events to callbacks, run the queue of ready ones. That is all. After this, the “magic of asyncio” stops being magic — it is a queue and epoll.
Lib/asyncio/tasks.py, the Task class. Consequence 4 is visible here: find _all_tasks and make sure it is a weak set. And the __step method — it does coro.send(None), that is, it resumes the frame in exactly the same way as the generator from lesson 13.
Lib/asyncio/taskgroups.py. A hundred and fifty lines implementing consequence 5: a list of tasks, cancelling the neighbours on the first error, collecting the exceptions into a group. Worth reading in full — it is the best short example of structured concurrency, and it shows that gather does none of this not through an oversight but because it appeared nine years earlier.
From L1 you know that await is a descendant of yield from. Here: exactly how it is built.
await x requires x to have an __await__ that returns an iterator. From there the same delegation mechanics work: values coming from that iterator are forwarded up the chain to the task, and the task passes them to the loop. The value that reaches the loop effectively says “I am waiting; wake me on this event”.
At the very bottom of the chain there is always a Future: its __await__ does a bare yield self. That is, the only place where suspension actually happens is the future; everything else just passes control through.
import inspect
c = co()
inspect.getcoroutinestate(c) # CORO_CREATED
c.cr_frame.f_lasti # the position, as for a generator
c.cr_await # what we are waiting on
The differences between a coroutine and a generator are formal, not mechanical: a separate type, no __iter__ (so that it cannot be walked by a loop by accident), and a ban on a bare yield inside async def. The frame, suspension and resumption are the very same.
About the price. Switching between coroutines is resuming a frame, that is, tens of nanoseconds; switching OS threads takes microseconds, processes more. Hence the orders of magnitude: tens of thousands of simultaneous coroutines are normal, tens of thousands of threads are not. But each coroutine holds a frame on the heap, so memory grows linearly with the number of tasks, and a million simultaneous connections will run up against exactly that.
Tag v3.11.15.
Objects/genobject.c — the coroutine type lives in the same place as the generator and reuses gen_send_ex. Direct confirmation that the mechanism is one.Lib/asyncio/ — the whole library in Python, nothing in C. It can be read in full in an evening; start with base_events.py and tasks.py.Modules/_asynciomodule.c — accelerated versions of Future and Task. Useful to know they exist: the Python versions in Lib are more readable, but these are usually the ones that run.async/await; the motivation says outright that the mechanism already worked on generators and syntax is being added.yield from channel all this grew fromexcept* and the exception groups with which TaskGroup is caughtLib/asyncio/base_events.py, the _run_once method — read it in full. Fifty lines after which the event loop stops being a black box.slow_callback_duration is useful.