async and await in Python
Defining coroutines and awaiting them in an event loop.
import asyncio
async def brew(drink, seconds):
print(f"brewing {drink}...")
await asyncio.sleep(seconds)
return f"{drink} ready"
async def main():
coffee = await brew("coffee", 0.1)
tea = await brew("tea", 0.1)
return [coffee, tea]
drinks = asyncio.run(main())
How it works
async defdeclares a coroutine function.awaitsuspends until the awaited task resolves.asyncio.run(main())drives the whole thing.
Keywords and builtins used here
asyncawaitbrewdefmainprintreturn
The run, in numbers
- Lines
- 16
- Characters to type
- 266
- Tokens
- 81
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 49 seconds.
Step 1 of 4 in Async, step 24 of 53 in Pythonic Python.