await — Advanced Playground
Pauses execution of an async coroutine until a result is available
Python Playground
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)}")
Output
Click "Run" to execute your code
Any object with __await__ can be used with 'await'. __await__ must return an iterator. Coroutines, Tasks, and Futures all implement this protocol.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?