python · level 3 · unit 5 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Two countdowns as tasks. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import asyncio
async def countdown(label, gap):
for n in [3, 2, 1]:
print(label, n)
await asyncio.sleep(gap)
async def main():
first = asyncio.create_task(countdown("A", 0.1))
second = asyncio.create_task(countdown("B", 0.15))
await first
await second
asyncio.run(main())
your turn
Your turn. Start the oven before washing up.
Fill the first blank so the baking starts in the background. In the second, await the task by its name.
fix it
The email task will not start. Fix it!
- Read the error: how many arguments does
create_tasktake? create_taskwants one ready-made coroutine, not a function followed by its arguments.- Call the coroutine inside it, as
asyncio.create_task(send_email("sam@example.com")), then run.
nailed it
you started work in the background. :D
asyncio.create_taskstarts a coroutine in the background.- Other work runs while the task waits.
await taskcollects the result. Always await your tasks.
new words in your collection
- task
- create_task
This lesson isn’t saved. A free account remembers every lesson you finish.