Python 3D Academyবাংলা

Limits and streams: Semaphore, async for, and gather's errors

🌍 In real life. A kitchen has two burners. Ten orders can come in at once, but only two pans fit on the stove; the rest wait for a free burner. Websites work the same way: send them 1,000 requests at once and they block you, so a polite program keeps only a few going at a time.

The idea in one sentence: an asyncio.Semaphore(n) holds n permits; async with sem: takes one before the block and gives it back after, so at most n coroutines are inside at once and the rest wait their turn, in order.

Its words:

  • Semaphore: a counter of free places; taking one when none are left means waiting
  • async with: like with (Chapter 28), but its entering and leaving can await, which is exactly what waiting for a permit needs
  • concurrency limit: the most things running at once
  • async generator: an async def with yield, whose items may take waiting to produce; loop over it with async for

What happens with 3 dishes and 2 burners, step by step:

  1. gather starts all three; tea and toast take the two permits and start cooking
  2. eggs reaches async with kitchen and finds no permit left, so it waits
  3. toast finishes and gives its permit back; eggs, first in line, takes it and starts
  4. everything finishes; the results still come back in the order you passed them

The grey bar is eggs waiting for a burner:

What it costs, by counting. With a limit of k and n jobs that each take t seconds, the jobs run in waves of k: about ⌈n / k⌉ × t. Ten 1-second downloads take about 1 s with no limit, 4 s with a limit of 3 (3 + 3 + 3 + 1), and 10 s one at a time. A limit trades a little speed for being kind to the server and to your own memory.

Streams with async for. A normal generator can't await between items. An async generator can: it is an async def with yield, and you read it with async for, or with an async comprehension, [x async for x in stream()]. Each item may take some waiting, like the next message from a chat server:

import asyncio

async def messages():
    for text in ["hi", "how are you?", "bye"]:
        await asyncio.sleep(0.01)          # waiting for the next one to arrive
        yield text

async def main():
    async for m in messages():
        print("got:", m)
    print([len(m) async for m in messages()])

asyncio.run(main())

When one job in a gather fails. By default, gather raises the first error it sees, and you lose the other results (the jobs that were still running carry on, unwatched). With return_exceptions=True, gather waits for everything and puts each error in the result list in place of a value, so you can sort the good from the bad. A TaskGroup (Lesson 32.3) takes the other path: it cancels the rest.

import asyncio

async def check(n):
    await asyncio.sleep(0.001 * n)
    if n % 2 == 0:
        raise ValueError(f"{n} is even")
    return n

async def main():
    try:
        await asyncio.gather(check(1), check(2), check(3))
    except ValueError as e:
        print("gather raised:", e)
    results = await asyncio.gather(check(1), check(2), check(3), return_exceptions=True)
    print(results)

asyncio.run(main())

Mistakes and edge cases.

  • a new Semaphore in every task: each task then has its own permits and nothing is limited; make one and share it
  • taking a permit without giving it back: await sem.acquire() with no release() slowly locks everyone out; async with always gives it back, even after an error
  • a plain for over an async generator: TypeError ("'async_generator' object is not iterable"); use async for, which only works inside async def
  • forgetting return_exceptions=True: one failure hides every other result
  • checking results with == Exception: an error in the list is an object; test it with isinstance(r, Exception)

Why limits and streams? A program that starts a thousand downloads at once can overwhelm a server or run out of memory; a Semaphore keeps only a few going at a time. And an async generator hands out results as they arrive, so the first ones can be used while the rest are still on their way.

Quiz

  1. What does this print?

    import asyncio
    
    gate = asyncio.Semaphore(1)
    
    async def job(name):
        async with gate:
            print("start", name)
            await asyncio.sleep(0.01)
            print("end", name)
    
    async def main():
        await asyncio.gather(job("a"), job("b"))
    
    asyncio.run(main())
  2. What does this print?

    import asyncio
    
    async def check(n):
        if n == 2:
            raise ValueError("bad")
        return n
    
    async def main():
        print(await asyncio.gather(check(1), check(2), return_exceptions=True))
    
    asyncio.run(main())
  3. What does this print?

    import asyncio
    
    async def ticks(n):
        for i in range(n):
            await asyncio.sleep(0)
            yield i
    
    async def main():
        total = 0
        async for t in ticks(4):
            total += t
        print(total)
    
    asyncio.run(main())
  4. 10 downloads take 1 second each. With asyncio.Semaphore(5) around each one, about how long does gather take?

    • About 2 seconds
    • About 1 second
    • About 10 seconds
  5. This stops with a TypeError. Which line is wrong?

    import asyncio
    
    async def ticks(n):
        for i in range(n):
            await asyncio.sleep(0)
            yield i
    
    async def main():
        for t in ticks(3):
            print(t)
    
    asyncio.run(main())

Coding tasks

  1. fetch pretends to download a page and records in peak the most downloads running at once. Fix fetch_all(urls, limit) so that no more than limit run at a time (use one asyncio.Semaphore), still returning the results in the order of urls.

  2. Make countdown_stream(n) an async generator: for n, n - 1, … down to 1, wait 0.001 seconds with asyncio.sleep and then yield the number. collect (written for you) reads it with an async comprehension.

  3. check(n) fails with a ValueError for even numbers. Write async def checked(nums): run check on every number together with gather, and return a pair: the list of good results (in order), and how many failed.