ZetCode

Python __await__ Method

Last modified November 17, 2026 Python 3.15

The await expression works with coroutines, futures, and any object that implements __await__. That method must return an iterator, which the event loop drives until it stops. This article explains the protocol, shows how to delegate to a coroutine correctly, and covers the mistakes that produce TypeError or a busy wait.

The await protocol

For await obj, Python calls type(obj).__await__() and requires an iterator. The event loop advances that iterator; when it raises StopIteration, the exception's value becomes the result of the await expression. A generator function is the simplest way to provide such an iterator. The following object waits for nothing and returns a constant.

constant_await.py
import asyncio
import inspect


class Constant:
    def __init__(self, value):
        self.value = value

    def __await__(self):
        yield from ()
        return self.value


async def main():
    value = Constant(42)
    print(inspect.isawaitable(value))
    print(await value)
    print(await value)


asyncio.run(main())

yield from () makes __await__ a generator that finishes immediately, and return self.value supplies the result. The object can be awaited more than once because every await calls __await__ again and gets a fresh generator. inspect.isawaitable reports true for the object.

$ python constant_await.py
True
42
42

Delegating to a coroutine

In practice, an awaitable usually wraps an asynchronous operation. The cleanest implementation returns the iterator of an internal coroutine: return self._fetch().__await__(). This delegates the whole protocol to the coroutine and avoids writing a generator by hand.

delegate_await.py
import asyncio


class Fetch:
    def __init__(self, url):
        self.url = url

    async def _fetch(self):
        await asyncio.sleep(0.1)
        return f"contents of {self.url}"

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


async def main():
    print("before await")
    result = await Fetch("https://example.com")
    print(result)
    print("after await")


asyncio.run(main())

Fetch.__await__ returns the iterator produced by _fetch. The event loop drives it through the sleep and then delivers the result to await. The three lines appear in order: before the await, the fetched value, and after the await.

$ python delegate_await.py
before await
contents of https://example.com
after await

Why yield from a coroutine fails

A coroutine object is awaitable, but it is not an iterator that a plain generator can delegate to with yield from. Python raises TypeError for yield from asyncio.sleep(...) inside a non-coroutine generator. Delegate to the coroutine's iterator with yield from asyncio.sleep(...).__await__(), or let an async def method perform the await and return its iterator from __await__.

broken_yield_from.py
import asyncio
import warnings

# Hide the unawaited-coroutine warning for this failing example.
warnings.filterwarnings("ignore", category=RuntimeWarning)


class Broken:
    def __await__(self):
        yield from asyncio.sleep(0.1)
        return "done"


async def main():
    try:
        await Broken()
    except TypeError as e:
        print(type(e).__name__, e)


asyncio.run(main())

The error occurs before the sleep can start. The warning filter at the top of the script hides the incidental "coroutine was never awaited" warning so that the actual TypeError is easy to see. This is a common mistake when adapting older generator-based code to the modern protocol.

$ python broken_yield_from.py
TypeError cannot 'yield from' a coroutine object in a non-coroutine generator

Wrapping a Future

asyncio.Future implements __await__, so a custom promise can delegate to a future and let another task set its result later. This bridges callback-style code with await without polling in a loop.

future_await.py
import asyncio


class Promise:
    def __init__(self):
        self._future = asyncio.get_running_loop().create_future()

    def set_result(self, value):
        if not self._future.done():
            self._future.set_result(value)

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


async def resolve_later(promise, value, delay):
    await asyncio.sleep(delay)
    promise.set_result(value)


async def main():
    promise = Promise()
    asyncio.create_task(resolve_later(promise, "result", 0.1))
    print("waiting")
    print(await promise)


asyncio.run(main())

Promise.__await__ returns the future's iterator, and resolve_later sets the result after a short delay. The awaiting task is suspended until the future is resolved, then prints result. A real implementation should also handle cancellation and avoid setting the result twice, which the done() check prevents.

$ python future_await.py
waiting
result

Chaining awaitables

An awaitable can combine other awaitables with yield from. Each delegation runs one operation to completion and returns its value, so the operations in the following example run sequentially. The final return value is the sum of the two results.

chain_await.py
import asyncio


class Add:
    def __init__(self, left, right):
        self.left = left
        self.right = right

    def __await__(self):
        left = yield from self.left.__await__()
        right = yield from self.right.__await__()
        return left + right


async def add_later(a, b, delay):
    await asyncio.sleep(delay)
    return a + b


async def main():
    total = Add(add_later(10, 20, 0.05), add_later(30, 40, 0.05))
    print(await total)


asyncio.run(main())

Add.__await__ first waits for add_later(10, 20) and then for add_later(30, 40). The total is 100. For concurrent execution, use asyncio.gather or a TaskGroup inside an async def function instead of chaining the awaitables one after another.

$ python chain_await.py
100

The return value must be an iterator

Two common mistakes are returning a plain value and returning a coroutine object. Both are awaitable in different senses, but neither is an iterator, so await raises TypeError before it can run anything. The error message names the method and the type it returned.

bad_await.py
import asyncio
import warnings

# Hide the unawaited-coroutine warning for this failing example.
warnings.filterwarnings("ignore", category=RuntimeWarning)


class NotAnIterator:
    def __await__(self):
        return 42


class CoroutineInstead:
    async def work(self):
        return "done"

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


async def main():
    for obj in (NotAnIterator(), CoroutineInstead()):
        try:
            await obj
        except TypeError as e:
            print(type(e).__name__, e)


asyncio.run(main())

NotAnIterator.__await__ returns 42, and CoroutineInstead.__await__ returns a coroutine. Python reports "must return an iterator" for both. A coroutine can be awaited directly, but it cannot be the return value of __await__; call its __await__() method to obtain the required iterator.

$ python bad_await.py
TypeError NotAnIterator.__await__() must return an iterator, not int
TypeError CoroutineInstead.__await__() must return an iterator, not coroutine

Best practices

Custom awaitables are rarely necessary, so keep them small and delegate when possible:

Source

object.__await__ - Python documentation

Awaitable objects - Python documentation

asyncio.Future - Python documentation

inspect.isawaitable - Python documentation

In this article we have implemented the __await__ method. We have covered the iterator protocol behind await, delegation to coroutines, the yield from pitfall, wrapping a future, chaining awaitables, and the required return type. For related topics, see Python async await, Python asyncio, Python __aenter__ method, Python __aiter__ method, and Python __anext__ method.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.