Code

Your First Coroutine

Most real programs spend their time waiting: for a web server to reply, a file to load, a timer to fire. While one job waits, the CPU sits idle. asyncio lets a single thread juggle many waiting jobs.

Three new words

  • async def defines a coroutine function. Calling it does not run the body. It hands you a coroutine object, a paused recipe.
  • await something runs another coroutine (or task) and pauses this one until the result is ready. While it is paused, other work can run.
  • asyncio.run(main()) starts the event loop, runs main() to the end, and returns its result.
import asyncio

async def fetch_map(island):
    await asyncio.sleep(0.1)  # pretend: network wait
    return f"map of {island}"

async def main():
    result = await fetch_map("Ember")
    print(result)

asyncio.run(main())  # map of Ember

Inside async code, use await asyncio.sleep(), never time.sleep(). time.sleep freezes the whole event loop, so nothing else can run while it waits.

Assignment

  1. Complete light_lantern(name): await asyncio.sleep(0.01), then return "<name> is lit" (for example "Ember is lit").
  2. Complete main(): await light_lantern("Ember"), then light_lantern("Frost"), and return both results in a list.
  3. Leave the last line as is. It runs main() and prints the list.