Skip to main content
Text ready — video coming soon

Trace async and await

The generator lesson showed that creating work and consuming it can happen at different moments. Asynchronous Python has a related distinction. Calling an async def function creates a coroutine object, a value representing a pending run of that asynchronous function. Awaiting or scheduling it lets that run proceed.

We will make those moments visible with a short local example. You will learn to:

  • Follow a coroutine through awaiting and scheduling.
  • Recognise a sequence consumed with async for.
  • Check waiting limits and cleanup around an operation.

These are the reading skills needed for the MCP client in the next lesson, where waiting involves an actual tool call.

Understand what can happen during a wait​

Suppose one operation is waiting for a network response. Concurrency allows progress on another operation during that wait. It does not necessarily mean two pieces of Python code are executing at the same instant on separate processors.

asyncio is Python's standard-library support for this style. Its event loop schedules work that cooperatively gives up control while waiting. An await can provide such a point, depending on the operation being awaited.

Adding async to a function does not automatically make ordinary blocking calls cooperative. If the body uses a blocking network client or spends a long time calculating without yielding, it can prevent other tasks on that event loop from making progress.

Follow a complete asynchronous call​

Save this as async_labels.py:

import asyncio

async def prepare_label(title):
await asyncio.sleep(0)
return f"Chapter: {title}"

async def main():
result = await prepare_label("Python and Roots")
print(result)

if __name__ == "__main__":
asyncio.run(main())

Run it with:

uv run python async_labels.py

The result is Chapter: Python and Roots.

async def defines a coroutine function. Calling main() creates its coroutine object. asyncio.run creates and manages an event loop for that top-level run. Inside it, await prepare_label(...) waits for the label operation to finish and obtains its returned string.

The sleep(0) deliberately gives the event loop an opportunity to run other scheduled work. It adds no useful book functionality; it is here to expose scheduling in a small language example. Formatting a string alone does not need asynchronous code. In the MCP client, the awaited operation will instead communicate through a real protocol connection.

Now remove await from the assignment in main. result becomes a coroutine object rather than the completed string. Python may also warn that the coroutine was never awaited. A coroutine-looking value in a log is evidence to inspect the call chain, not a finished tool answer.

Schedule independent operations deliberately​

Two await statements written one after another normally wait in sequence. If the work is independent, gather can schedule it together:

async def main():
results = await asyncio.gather(
prepare_label("Python and Roots"),
prepare_label("Python and Branches"),
)
print(results)

This replaces main in the complete file above; keep the import, prepare_label and guarded asyncio.run call. results contains the returned values in the argument order, even if the operations finish in a different order.

asyncio.create_task is another form you will recognise. It schedules a coroutine on the running loop and returns a task that can be awaited later. Scheduling and forgetting a task is not a completion check. Decide who waits for it and who handles its failure.

More concurrency can also mean more simultaneous requests, more open connections or more cost. A service may limit how many calls it accepts. A real solution therefore needs a deliberate concurrency limit, rather than launching one task for every input without a bound.

Recognise a sequence that can wait between items​

An asynchronous iterator can wait while obtaining its next item. You consume it with async for. Here is a complete separate script using the two published chapter titles:

import asyncio
from typing import AsyncIterator

async def chapter_titles() -> AsyncIterator[str]:
for title in ("Python and Roots", "Python and Branches"):
await asyncio.sleep(0)
yield title

async def show_titles():
async for title in chapter_titles():
print(title)

asyncio.run(show_titles())

It prints the two titles in order. Combining async def with yield creates an asynchronous generator. AsyncIterator[str] describes its expected sequence of string values. Unlike the coroutine function earlier, this function supplies items to async for; you do not obtain the sequence by awaiting chapter_titles() itself.

Recognise this shape when a framework streams events. It still needs a rule for failure and completion. The Python reference for asynchronous iteration defines the loop; the annotation does not enforce the truth of every yielded item.

Bound the wait and keep cleanup attached​

An external operation may never return in the way you hoped. asyncio.wait_for can bound an await:

result = await asyncio.wait_for(
prepare_label("Python and Roots"),
timeout=5,
)

This line belongs inside an asynchronous function. Five seconds is an explicit policy choice for the example, not a universal safe timeout. If the wait times out, Python raises TimeoutError; the code must decide what outcome to return or report.

Cancellation of local waiting does not prove a remote side effect was undone. That matters for tools that send messages, change files or charge money. Our coming lookup tool is read-only, which makes its consequences easier to reason about.

async with manages entering and leaving an asynchronous resource, such as a client session. Like the file's with block, it keeps cleanup attached to the operation. It does not suppress every error or grant extra permission to the caller.

Safety floor

Bound external waits and the amount of concurrent work. Keep track of scheduled tasks and their failures. Before retrying an operation that changes something, establish whether the earlier attempt already performed that change; cancelling a wait alone does not answer that question.

Use Python's coroutine and task guide and its advice on blocking code for the underlying rules. These scripts assume a terminal run; an environment with an already running event loop needs its own documented way to await the top-level coroutine.

Account for the work from call to result​

Before looking at the comparison:

  1. What is produced by calling prepare_label(...) without awaiting or scheduling it?
  2. Does async def make a blocking library call stop blocking?
  3. How does two-step sequential awaiting differ from gather for independent operations?
  4. What does a local timeout fail to prove about a remote write?
  5. Which resource-management form will you expect around an asynchronous client session?
Check after your attempt

The call produces a coroutine object. A blocking operation remains blocking unless deliberately handled appropriately. Sequential awaits wait for one result before starting the next call; gather can schedule independent operations concurrently. A timeout does not prove a remote action was rolled back. An async with block commonly attaches session cleanup to its use.

The next lesson uses these Python pieces to build a local MCP server and inspect a real tool call. You now have enough language underneath it to ask what each framework line adds.