awaitExpert Examples

Pauses execution of an async coroutine until a result is available

Await bytecode: GET_AWAITABLE

How await compiles and interacts with the event loop.

python
import dis
import asyncio

async def simple_await():
    await asyncio.sleep(0)
    return 1

async def multi_await():
    a = await asyncio.sleep(0)
    b = await asyncio.sleep(0)
    return a, b

print("Single await:")
dis.dis(simple_await)
print("\nMultiple awaits:")
dis.dis(multi_await)

# await compiles to:
# 1. Evaluate the awaitable expression
# 2. GET_AWAITABLE - calls __await__() to get iterator
# 3. LOAD_CONST None
# 4. SEND / YIELD_VALUE - yield control to event loop
# The event loop drives the coroutine via send()

await compiles to GET_AWAITABLE (which calls __await__) followed by SEND. The event loop drives coroutines by repeatedly calling send(None) until StopIteration, which carries the return value.

Want to try these examples interactively?

Open Expert Playground