×

python · level 3 · unit 5 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.