python · level 3 · unit 5 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
waits for several things at once.
Awaiting three slow replies one after another means three waits in a row. With asyncio.gather, all three start together, and while one waits the event loop runs the others. This is : one worker switching jobs instead of standing idle.
gather hands back a list of results in the order you passed the coroutines in, whichever finished first. The whole wait lasts about as long as the slowest reply, not all of them added up.
import asyncio
import json
REPLIES = {"ana": '{"likes": 120}', "ben": '{"likes": 45}', "cara": '{"likes": 300}'}
async def likes_for(user, delay):
await asyncio.sleep(delay)
print("got", user)
return json.loads(REPLIES[user])["likes"]
async def main():
counts = await asyncio.gather(likes_for("ana", 0.3), likes_for("ben", 0.1), likes_for("cara", 0.2))
print(counts, sum(counts))
asyncio.run(main()) Concurrency helps with waiting, like web requests, not with heavy sums, because only one job runs at any moment.
guess first
The salad is quicker than the pizza. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import asyncio
async def order(dish, wait):
await asyncio.sleep(wait)
print("ready:", dish)
return dish
async def main():
dishes = await asyncio.gather(order("pizza", 0.3), order("salad", 0.1))
print(dishes)
asyncio.run(main())
your turn
Your turn. Fetch three prices at once.
Fill the first blank with the function that runs coroutines together. Then pick two more items from PRICES for the other blanks.
fix it
Pinging every server crashes. Fix it!
- Read the error:
gatherwanted coroutines, but what did it get? jobsis one list.gatherwants each coroutine as its own argument.- Spread the list with a star, as
asyncio.gather(*jobs), then run.
nailed it
you did three things at once. :D
asyncio.gatherruns coroutines together.- Results come back in the order you passed them.
- The total wait is about as long as the slowest job.
new words in your collection
- concurrency
- gather
This lesson isn’t saved. A free account remembers every lesson you finish.