
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 defdefines a coroutine function. Calling it does not run the body. It hands you a coroutine object, a paused recipe.await somethingruns 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, runsmain()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
- Complete
light_lantern(name):await asyncio.sleep(0.01), then return"<name> is lit"(for example"Ember is lit"). - Complete
main(): awaitlight_lantern("Ember"), thenlight_lantern("Frost"), and return both results in a list. - Leave the last line as is. It runs
main()and prints the list.
- Complete
light_lantern(name):await asyncio.sleep(0.01), then return"<name> is lit"(for example"Ember is lit"). - Complete
main(): awaitlight_lantern("Ember"), thenlight_lantern("Frost"), and return both results in a list. - Leave the last line as is. It runs
main()and prints the list.
main.py Python sleeping
Press Run to try your code, then Check to test it.