typestar

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

  1. async def declares a coroutine function.
  2. await suspends until the awaited task resolves.
  3. asyncio.run(main()) drives the whole thing.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 4 in Async, step 24 of 53 in Pythonic Python.

← Previous Next →

async and await in other languages