Sub topic 1
Coroutines, tasks, and the event loop in brief
Every later chapter in this tutorial (task groups, timeouts, cancellation) depends on one model: coroutines are the work, tasks schedule the work, and the event loop runs it. This chapter builds that model and shows the errors people hit when it is wrong.
Prerequisites
This chapter assumes you have:
- Python 3.11 or newer installed.
- Working knowledge of
async defandawait. - Familiarity with
try/except/finallyand with context managers (withandasync with). - Some experience running code through
asyncio.run.
Three pieces
- A coroutine function is a function defined with
async def. Calling it does not run its body. It returns a coroutine object, which holds the paused function and its state. - A task is an object that wraps a coroutine and registers it with the event loop. The loop drives the coroutine to completion, and the task stores the outcome (a result, an exception, or a cancelled state).
- The event loop is a scheduler that runs in one thread. It keeps a set of tasks that are ready to run, runs one until it reaches an
awaitthat cannot continue yet, then switches to another.
Concurrency in asyncio is cooperative. Only one task runs at any moment, and a task gives up control only when it awaits something that is not ready.
A coroutine object does nothing by itself
import asyncio
async def greet():
print("running body")
return "hello"
coro = greet() # nothing printed yet
print(type(coro)) # <class 'coroutine'>
print(asyncio.run(coro))The body prints only inside asyncio.run. If you create a coroutine object and never await it or wrap it in a task, Python emits RuntimeWarning: coroutine 'greet' was never awaited. That warning almost always means a missing await.
Awaiting versus scheduling
There are two ways to run a coroutine from inside another coroutine, and they behave differently.
await coro()runs the coroutine to completion before the next line executes. The caller waits, and no new concurrency appears.asyncio.create_task(coro())wraps the coroutine in a task and schedules it. The caller continues at once, and the new task runs whenever the caller next yields to the loop.
import asyncio
import time
async def work(name, delay):
await asyncio.sleep(delay)
return name
async def sequential():
start = time.perf_counter()
await work("a", 0.2)
await work("b", 0.2)
print(f"sequential: {time.perf_counter() - start:.1f}s")
async def concurrent():
start = time.perf_counter()
t1 = asyncio.create_task(work("a", 0.2))
t2 = asyncio.create_task(work("b", 0.2))
await t1
await t2
print(f"concurrent: {time.perf_counter() - start:.1f}s")
async def main():
await sequential()
await concurrent()
asyncio.run(main())This prints about 0.4s for the sequential version and about 0.2s for the concurrent one. In the concurrent version, both tasks sleep at the same time because the loop switches between them whenever one is waiting.
What the loop does
The following diagram shows one task yielding to the loop at an await, and the loop resuming it when the awaited thing is ready.
Two details in the diagram matter later:
- A task created with
create_taskdoes not start until the creating task yields. If the creator never awaits anything, the child never runs. - Every
awaiton something unfinished is a point where the loop may switch tasks. These are also the only points where cancellation can be delivered, which is the subject of the cancellation chapters.
Task state and results
A task is always in one of these conditions, and you can inspect it.
| Condition | `done()` | `cancelled()` | `result()` | `exception()` |
|---|---|---|---|---|
| Pending or running | `False` | `False` | raises `InvalidStateError` | raises `InvalidStateError` |
| Finished normally | `True` | `False` | the return value | `None` |
| Raised an exception | `True` | `False` | re-raises it | the exception |
| Cancelled | `True` | `True` | raises `CancelledError` | raises `CancelledError` |
Awaiting a task returns its result or raises its exception, so you rarely call result() directly. It is still useful after a block that is guaranteed to have waited for the task, such as the async with form of a task group shown in a later chapter.
If a task fails and nobody ever awaits it or reads its exception, asyncio logs Task exception was never retrieved when the task object is garbage collected. The error is not raised anywhere else, so it is easy to miss.
The loop is single-threaded
Because only one task runs at a time, any code that does not await blocks every other task. This includes time.sleep, synchronous network calls, heavy computation, and large file reads.
import asyncio
import time
async def ticker():
for i in range(3):
print("tick", i)
await asyncio.sleep(0.1)
async def main():
t = asyncio.create_task(ticker())
await asyncio.sleep(0) # yield once so the ticker starts
time.sleep(0.5) # blocks the whole loop: no ticks for 0.5s
# Better: await asyncio.to_thread(time.sleep, 0.5)
await t
asyncio.run(main())The first tick prints, then nothing happens for half a second, because time.sleep never yields to the loop. Replacing it with await asyncio.to_thread(time.sleep, 0.5) runs the blocking call in a worker thread, and the ticker keeps running.
The same applies to timeouts and cancellation. A deadline can only be enforced at an await, so a task stuck in blocking code cannot be interrupted until it returns to the loop.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `RuntimeWarning: coroutine '...' was never awaited` | Called an async function without `await` or a task wrapper | Add `await`, or pass the coroutine to `create_task` |
| `RuntimeError: no running event loop` | Called `create_task` from ordinary synchronous code | Call it from inside a coroutine started by `asyncio.run` |
| `RuntimeError: asyncio.run() cannot be called from a running event loop` | Nested `asyncio.run`, common in notebooks | `await` the coroutine instead |
| Tasks run one after another | Used `await` on each coroutine in turn | Create tasks first, then wait for them |
| Everything freezes for a while | Blocking call inside a coroutine | Use an async library, or `asyncio.to_thread` |
| `Task exception was never retrieved` | A failed task was never awaited | Await the task, or use a task group |
asyncio.run creates a fresh event loop, runs the coroutine you give it until it finishes, then cancels any tasks still pending and closes the loop. It is meant to be the single entry point of a program.
Where the rest of the tutorial goes
You now have the working model: a coroutine is paused work, a task is that work registered with the loop, and the loop switches tasks only at await. The next chapters keep that model and add control over it. They cover how to start and keep track of tasks, how to stop them with cancellation, and how task groups and timeouts make both predictable.
Exercise
In the code below, what does it print, and why? Where would you add a single line to make "child ran" appear before "main done"? import asyncio async def child(): print("child ran") async def main(): asyncio.create_task(child()) print("main done") asyncio.run(main())
Show answer
It prints only "main done". create_task schedules the child but does not start it, and main never awaits anything, so it returns without yielding to the loop. asyncio.run then cancels the pending child before it runs. Adding await asyncio.sleep(0) before the print lets the child run first. A better fix is to keep the task in a variable and await it, which also guarantees the child finishes.
Exercise
A coroutine calls requests.get(url) (a synchronous HTTP call) inside an async def, and other tasks appear to stall while it runs. Why does this happen, and what are two ways to fix it?
Show answer
The call never awaits, so the single-threaded loop cannot switch to other tasks until it returns. Fix it by using an async HTTP client and awaiting its calls, or by running the blocking call in a worker thread with await asyncio.to_thread(requests.get, url).