Waiting without wasting time: async and await
🌍 In real life. Making breakfast, you switch the kettle on. It takes three minutes to boil, and you don't stand staring at it: you make toast while you wait. A lot of programs spend most of their time waiting too: for a website to answer, a file to arrive, a timer to ring.
The idea in one sentence: an async def function can pause at every await, and while it is paused, the event loop runs other paused functions that are ready to go on, so one worker gets through many waits at once.
Its words:
- coroutine function: a function written with
async def - coroutine: what calling it gives back: a paused piece of work that hasn't started yet (like a generator from Chapter 26)
- await: "pause me here until that is finished"; it only works inside
async def - event loop: the part of asyncio that keeps the paused coroutines and decides which one runs next
- cooperative: a coroutine gives way only at an
await; between two awaits it runs on its own
What asyncio.run(main()) does, step by step:
- it starts an event loop and hands it the coroutine
main() - the loop runs main's lines until main reaches an
await await asyncio.sleep(0.3)sets a timer and hands control back to the loop (time.sleepwould freeze the whole program instead)- the loop runs anything else that is ready; when the timer rings, main carries on from the line after the await
- when main returns,
asyncio.rungives back its value and closes the loop
import asyncio
async def greet():
print("hello")
return "done"
c = greet()
print(type(c).__name__)
c.close()
print(asyncio.run(greet()))Watch one dish after another. Here main awaits the tea, and only when the tea is done does it await the toast. Each dish has a lane. The gold blip is Python running its lines; the blue bar is the time it spends waiting on asyncio.sleep. Notice that while the tea waits, the toast lane is empty: await made main wait.
import asyncio
async def cook(dish, secs):
print("start", dish)
await asyncio.sleep(secs)
print("done", dish)
return dish
async def main():
a = await cook("tea", 0.3)
b = await cook("toast", 0.1)
print([a, b])
asyncio.run(main())Why it works. The event loop is a simple queue (Lesson 32.4 builds one from generators). A coroutine runs until its next await, then steps aside; the loop wakes whichever paused coroutine is ready next. Because the switch can happen only at an await, no two lines ever run at the same moment: between awaits a coroutine has Python to itself, so it can't be interrupted halfway through updating a list. The other side of that promise: a coroutine that never awaits never lets anyone else run (Lesson 32.5).
What it costs, by counting. Awaiting one thing after another costs the sum of the waits: tea then toast is 0.3 + 0.1 = 0.4 s, and 10 downloads of 1 second each, awaited in turn, take 10 seconds. Lesson 32.2 lets the waits overlap, so the same 10 take about 1 second. Switching itself costs only microseconds, but it saves time only while something is waiting (a network, a disk, a timer); for heavy calculating, one worker taking turns is no faster (Lesson 32.4).
Mistakes and edge cases.
- forgetting
await:cook("tea", 0.3)on its own makes a coroutine and throws it away: nothing runs, and Python warns "coroutine 'cook' was never awaited" awaitoutsideasync def: a SyntaxError ("'await' outside async function")asyncio.runinside async code: it starts a new loop, and one is already running, so it fails with a RuntimeError; inside async code, justawaittime.sleepinside async code: it doesn't await, so it freezes every coroutine (Lesson 32.5)- awaiting something that isn't awaitable:
await 5is a TypeError; you can await coroutines, tasks and other awaitables
Quiz
What does this print?
import asyncio async def main(): print("a") await asyncio.sleep(0.1) print("b") return 7 print(asyncio.run(main()))What happens when you call an
async deffunction, likegreet(), without await or asyncio.run?- It makes a coroutine; none of its body runs yet
- It runs the body straight away
- It raises an error
Inside async code, why use
await asyncio.sleep(1)rather thantime.sleep(1)?- time.sleep freezes everything; asyncio.sleep lets other work run meanwhile
- asyncio.sleep is more accurate
- time.sleep doesn't work in functions
What does this print?
import asyncio async def cook(dish): print("start", dish) await asyncio.sleep(0.1) print("done", dish) async def main(): await cook("rice") await cook("dal") asyncio.run(main())Inside
main, the linecook("tea", 0.3)has noawaitin front. What happens?- A coroutine is made and thrown away: the tea never cooks, and Python warns it was never awaited
- The tea cooks in the background
- main waits for the tea anyway
Which line has a mistake?
import asyncio def boil(): await asyncio.sleep(0.1) return "tea" print(asyncio.run(boil()))
Coding tasks
Write
async def double_later(n): wait 0.01 seconds withasyncio.sleep, then give backn * 2.cookis written for you and writes what it does intolog. Finishasync def main(): cook"rice"for 0.02 seconds, then"dal"for 0.01, and give back the two results in a list.Write
async def countdown(n): printn,n - 1, … down to1, waiting 0.01 seconds withasyncio.sleepafter each number, then printliftoff. (The last line runs it.)