Python 3D Academyবাংলা

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:

  1. it starts an event loop and hands it the coroutine main()
  2. the loop runs main's lines until main reaches an await
  3. await asyncio.sleep(0.3) sets a timer and hands control back to the loop (time.sleep would freeze the whole program instead)
  4. the loop runs anything else that is ready; when the timer rings, main carries on from the line after the await
  5. when main returns, asyncio.run gives 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()))
greet() made a coroutine and ran nothing: "hello" only appears once asyncio.run starts it. (c.close() throws the unused one away.) In this app, asyncio.run needs Chrome or Edge; Safari and Firefox are adding what it needs.

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())
This is the program the timeline played. Waiting this way takes 0.3 + 0.1 seconds. The next lesson makes the two waits overlap.

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"
  • await outside async def: a SyntaxError ("'await' outside async function")
  • asyncio.run inside async code: it starts a new loop, and one is already running, so it fails with a RuntimeError; inside async code, just await
  • time.sleep inside async code: it doesn't await, so it freezes every coroutine (Lesson 32.5)
  • awaiting something that isn't awaitable: await 5 is a TypeError; you can await coroutines, tasks and other awaitables

Quiz

  1. What does this print?

    import asyncio
    
    async def main():
        print("a")
        await asyncio.sleep(0.1)
        print("b")
        return 7
    
    print(asyncio.run(main()))
  2. What happens when you call an async def function, like greet(), 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
  3. Inside async code, why use await asyncio.sleep(1) rather than time.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
  4. 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())
  5. Inside main, the line cook("tea", 0.3) has no await in 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
  6. Which line has a mistake?

    import asyncio
    
    def boil():
        await asyncio.sleep(0.1)
        return "tea"
    
    print(asyncio.run(boil()))

Coding tasks

  1. Write async def double_later(n): wait 0.01 seconds with asyncio.sleep, then give back n * 2.

  2. cook is written for you and writes what it does into log. Finish async def main(): cook "rice" for 0.02 seconds, then "dal" for 0.01, and give back the two results in a list.

  3. Write async def countdown(n): print n, n - 1, … down to 1, waiting 0.01 seconds with asyncio.sleep after each number, then print liftoff. (The last line runs it.)