[Python] Why must an object used with await implement __await__() that returns an iterator in...

Discussão em 'Python' iniciado por Stack, Agosto 23, 2025.

  1. Stack

    Stack Membro Participativo

    I am learning Python asyncio and trying to understand how await works. I know that when I write an async function:

    async def foo():
    result = await meet
    print(result)


    Calling foo() returns a coroutine object.

    When the code hits await meet, Python expects meet to be awaitable.

    I read that an object is awaitable if it implements a __await__() method that returns an iterator. For example:

    class Meet:
    def __await__(self):
    yield "Hello"
    return "World"

    meet = Meet()


    Then I can do:

    coro = foo().__await__()
    t = next(coro)


    My question is why the object after await must implement __await__() that returns an iterator.

    What is the logic behind requiring an iterator?

    What happens under the hood when Python iterates over this iterator after await?

    Could we have designed await to work with any object, not necessarily one returning an iterator?

    I want to understand why Python enforces that __await__() must return an iterator and what internally happens when await iterates over it.

    Continue reading...

Compartilhe esta Página