What Can Python Await? Writing Awaitable Objects with __await__

This article explains how the __await__ protocol makes any Python object awaitable, how to delegate it to a coroutine, which values asyncio accepts from it, and why a custom awaitable offers control rather than speed.

A green tree python coiled around a thick branch, resting its head on its coils as if waiting
Photo by David Valentine on Unsplash

Most asynchronous Python code awaits coroutines created with async def, tasks and futures, without asking what makes an object acceptable to await. The present article addresses the protocol behind that keyword: an object is awaitable when it implements __await__, a method that returns an iterator through which the object suspends and resumes. Turn-based strategy games provide an appropriate image: a unit that starts a long action ends its turn, the game lets the other units act, and in a later round the same unit continues exactly where it stopped. This means that each suspension inside __await__ hands control back to the event loop, which runs other tasks and resumes the suspended one later, while the value that the iterator finally returns becomes the result of the await expression. The analogy, however, stops at this point, because there is no fixed order of turns: the event loop resumes a task when what it waits for is ready, and a task that never suspends never gives up its turn. The article writes awaitable classes, shows how to delegate to a coroutine, examines the errors that the event loop raises, and measures the cost of the protocol. Making any object a legitimate target of await, with full control over when it suspends and what it returns, is the secret weapon of __await__.

The await Protocol

The data model requires __await__ to return an iterator, and in practice the method is written as a generator, the mechanism described in the article devoted to yield. Each yield suspends the awaiting coroutine, and the return value of the generator, carried by StopIteration as explained in the article devoted to the iterator protocol, becomes the result of await. The language itself imposes no restriction on the values yielded, because they are a message to the framework that drives the coroutine, and in asyncio a bare yield asks only to be resumed on the next iteration of the loop.

import asyncio
import inspect
from collections.abc import Awaitable

class Checkpoint:
    def __init__(self, label):
        self.label = label

    def __await__(self):
        print(f"{self.label}: suspended")
        yield
        print(f"{self.label}: resumed")
        return self.label.upper()

async def worker(name):
    return await Checkpoint(name)

async def main():
    print(await asyncio.gather(worker("a"), worker("b")))

asyncio.run(main())
print(inspect.isawaitable(Checkpoint("x")), isinstance(Checkpoint("x"), Awaitable))
# Output: a: suspended
# Output: b: suspended
# Output: a: resumed
# Output: b: resumed
# Output: ['A', 'B']
# Output: True True

Both workers suspend before either resumes, which shows that each bare yield returned control to the event loop, and each await produces the value returned by the generator. The functions inspect.isawaitable and isinstance with collections.abc.Awaitable recognize the class because it defines __await__, so code that accepts awaitables can check for it without knowing the concrete type.

Delegating to a Coroutine

Writing the suspension logic by hand is rarely necessary, because __await__ can delegate to a coroutine method and return that coroutine's own iterator. Unlike a coroutine object, which can be awaited only once, such a class creates a fresh coroutine on every await, so the same instance can be awaited repeatedly.

import asyncio

class Config:
    async def _load(self):
        await asyncio.sleep(0)
        return {"debug": False}

    def __await__(self):
        return self._load().__await__()

async def fetch():
    return 1

async def main():
    config = Config()
    print(await config, await config)  # Output: {'debug': False} {'debug': False}
    coro = fetch()
    await coro
    try:
        await coro
    except RuntimeError as error:
        print(error)  # Output: cannot reuse already awaited coroutine

asyncio.run(main())

The pattern lets an ordinary object, such as a configuration or a connection being established, be awaited with all the facilities of async def inside _load. The coroutine coro, by contrast, is exhausted after its first await, and since Python 3.5.2 a second await raises RuntimeError.

Pitfalls of Awaitable Objects

The protocol connects an object to a framework through values that only the framework understands, so most errors come from yielding the wrong thing, returning the wrong object or expecting a speed that the protocol does not offer. Six pitfalls are distinguished, which are the following:

  1. Yielding arbitrary values. asyncio accepts a bare yield and futures; any other value raises RuntimeError: Task got bad yield.
  2. Returning a coroutine. __await__ must return an iterator, so returning the coroutine itself raises TypeError and leaves it never awaited.
  3. Blocking inside __await__. Code that blocks, such as time.sleep, stops the whole event loop, because only a yield gives control back.
  4. Awaiting a coroutine twice. A coroutine object is exhausted after one await; reusable awaitables must create a new one each time.
  5. Framework coupling. The values yielded are specific to asyncio, so a hand-written __await__ may not work under another framework.
  6. Assuming speed. A custom __await__ creates a generator on every await, which is slower, not faster, than awaiting a coroutine.

The first, second and sixth pitfalls are reproduced in the following example.

import asyncio
import time

class BadYield:
    def __await__(self):
        yield 42

class ReturnsCoroutine:
    async def _run(self):
        return 1

    def __await__(self):
        return self._run()

class Ready:
    def __await__(self):
        return 1
        yield

async def plain():
    return 1

async def main():
    try:
        await BadYield()
    except RuntimeError as error:
        print(error)  # Output: Task got bad yield: 42
    try:
        await ReturnsCoroutine()
    except TypeError as error:
        print(error)  # Output: __await__() returned a coroutine
    start = time.perf_counter()
    for _ in range(100_000):
        await Ready()
    custom = time.perf_counter() - start
    start = time.perf_counter()
    for _ in range(100_000):
        await plain()
    native = time.perf_counter() - start
    print(custom > native)  # Output: True

asyncio.run(main())

The event loop rejects the value 42 because it is neither None nor a future, and the interpreter rejects the coroutine because it is not an iterator; it also emits a warning that the coroutine was never awaited. On CPython 3.12, awaiting Ready took about 105 nanoseconds against about 56 for an equivalent async def, so the protocol offers control, not speed.

Choosing How to Make Something Awaitable

Consequently, a hand-written __await__ is justified only when an object must decide exactly how it suspends, as the following table summarizes.

Situation Recommended approach
An asynchronous operation with a result An async def coroutine
An object that should be awaited for its initialization or result __await__ delegating to a coroutine method
A value that will be set later by another part of the program asyncio.Future, created with loop.create_future()
Running a coroutine concurrently asyncio.create_task
A custom suspension point in a low-level library __await__ written as a generator
Checking whether an object can be awaited inspect.isawaitable
Blocking or CPU-bound work asyncio.to_thread or a process pool

The choice between asynchronous code, threads and processes as a whole is examined in the article devoted to concurrency models.

Conclusion

It is concluded that an object is awaitable when its __await__ returns an iterator, that each value yielded is a message to the event loop and the returned value becomes the result of await, and that delegating to a coroutine method produces objects that can be awaited repeatedly. This magic serves control rather than speed: asyncio accepts only bare yields and futures, __await__ must never return a coroutine, and each custom await costs more than a native one. Defining __getattr__ at module level, so that a module can supply attributes on demand or warn about deprecated names, is the subject of a future article of this series.