×

python · level 3 · unit 5 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A starts work now so you can collect it later.

Awaiting a coroutine starts it and waits on the spot. Sometimes you want to start something slow, do other work, and only wait when you need the answer. does that: it turns a coroutine into a task that runs in the background.

The task makes progress whenever your code awaits anything. Later, await task hands back its result, at once if it has already finished.

Keep a name for every task you create, and await it before main ends.

import asyncio
async def download(name):
    print("downloading", name)
    await asyncio.sleep(0.2)
    return f"{name} saved"

async def main():
    task = asyncio.create_task(download("photos.zip"))
    print("tidying the inbox meanwhile")
    await asyncio.sleep(0.1)
    print("inbox tidy")
    print(await task)

asyncio.run(main())

A task does not start the moment you create it, only at the next await that lets the event loop run.