Skip to content

Await and iteration

Python blocks return coroutines, generators and async generators, and each of those stays in the process that created it. The CPython provider settles them itself: it owns one explicit asyncio.Runner per process, runs awaitables to completion on it, and advances iterators one step at a time on request. What leaves the provider is the settled value or the next item. This page covers how a result is settled, how iterators are advanced, and what happens to the runner at shutdown.

Settling a result

flowchart TB
  AD["Generated adapter<br/>returns a raw result"]
  D{{"Delivery declared by the interface"}}
  subgraph RUNBOX["ONE ASYNCIO RUNNER"]
    direction TB
    AW["Run the awaitable to completion"]
    IT[("Provider-local iterator<br/>sync or async")]
  end
  V["Typed value"]
  P["Stream proposal"]
  ERR["Declared-error adaptation"]
  AD --> D
  D -->|"future, or a value method<br/>that returned an awaitable"| AW
  D -->|"stream"| IT
  AW --> V
  AW -.->|"exception raised while awaiting"| ERR
  IT --> P

Dispatch calls the generated adapter, then settles the raw result according to the delivery the interface declares:

  • a method declared as a future must return an awaitable, and the provider runs it on the runner;
  • a value method that returns an awaitable is settled the same way;
  • an exception raised while awaiting is kept inside the process long enough to pass through declared-error adaptation, so an awaited declared error reaches the caller as that declared error;
  • a stream result is normalised to a provider-local synchronous or asynchronous iterator before it is offered outside the provider.

See Exception adaptation and result classification.

Advancing an iterator

An iterator stays in the provider resource table, and each advance returns one item. StopIteration and StopAsyncIteration are recognised as exhaustion. Asynchronous steps run on the same runner as every other awaitable.

Opening a provider stream produces a proposal. The kernel-visible stream, its authority and its stream syscalls are created by the monitor and the nucleus when they promote that proposal. See Stream and buffer authority.

Shutdown

Cooperative termination closes the runner first, then reports whether the provider released its local state cleanly. See Health, quiesce, terminate and Event loop ownership.