awaitAdvanced Examples

Pauses execution of an async coroutine until a result is available

Awaitable protocol

Making custom objects awaitable.

python
import asyncio

class AsyncResult:
    def __init__(self, value, delay=0):
        self.value = value
        self.delay = delay

    def __await__(self):
        # Must return an iterator
        if self.delay:
            yield from asyncio.sleep(self.delay).__await__()
        return self.value

async def main():
    result = await AsyncResult(42, 0.01)
    print(f"Got: {result}")

    # Chain awaitables
    a = await AsyncResult(10)
    b = await AsyncResult(20)
    print(f"Sum: {a + b}")

asyncio.run(main())

# Check what's awaitable
print(f"\ncoroutine awaitable: {hasattr(main, '__await__') or asyncio.iscoroutinefunction(main)}")
Expected Output
Got: 42
Sum: 30
coroutine awaitable: True

Any object with __await__ can be used with 'await'. __await__ must return an iterator. Coroutines, Tasks, and Futures all implement this protocol.

Want to try these examples interactively?

Open Advanced Playground