Terminal

afonso's little corner

← back to home
python

the fast and the async: a literal python script

by afonso2025-09-17

THE FAST AND THE ASYNC: A LITERAL PYTHON SCRIPT

Directed by Afonso Delgado
EXT. NIGHT MARKET - NIGHT
Neon lights flicker. Food stalls sizzle. A crowd that never stops moving. At the center stands the DISPATCHER, the event loop, calmly directing traffic so no one waits longer than needed. Runners dart between stalls with tickets in hand; these are your COROUTINES. Every time they hit a line, they step aside and another runner takes the lane. The market hums, not because everyone is rushing, but because no one is stuck.
INT. PYTHON INTERPRETER - CONTINUOUS
NARRATOR
Async shines when your story has a lot of waiting: APIs, databases, files, websockets. When one character pauses, another advances. The goal is throughput, not raw speed.
EXT. CASTING CALL - DAY
DIRECTOR
Meet the cast:
  • event loop - the dispatcher that keeps the market flowing
  • coroutines - runners defined with async def
  • await - the polite step aside while you wait in line
  • tasks - tickets that let runners advance together
INT. SMALLEST POSSIBLE ASYNC - NIGHT
PYTHON
Define a coroutine with async def, then run it with asyncio.run.
1import asyncio
2
3async def greet():
4    await asyncio.sleep(0.1)
5    print("hello from async")
6
7asyncio.run(greet())
OUTPUT
hello from async
INT. CONCURRENCY ON ONE LOOP - NIGHT
DISPATCHER
I hand three tickets to three runners. With asyncio.gather, they move through the lines separately. Total time equals the longest queue, not the sum of all waits.
1import asyncio, time
2
3async def fetch(name, delay):
4    await asyncio.sleep(delay)
5    print(f"fetched {name}")
6    return name
7
8async def main():
9    t0 = time.perf_counter()
10    results = await asyncio.gather(
11        fetch("alpha", 0.4), fetch("bravo", 0.2), fetch("charlie", 0.3)
12    )
13    dt = time.perf_counter() - t0
14    print("results:", results)
15    print(f"elapsed: {dt:.2f}s")
16
17asyncio.run(main())
OUTPUT
fetched bravo fetched charlie fetched alpha results: ['alpha', 'bravo', 'charlie'] elapsed: 0.40s
INT. TIMEOUTS AND CANCELLATION - NIGHT
DISPATCHER
Sometimes a line stalls. I set a timer with asyncio.wait_for. If it rings, the ticket is voided and the runner steps back so others can move.
1import asyncio
2
3async def slow():
4    try:
5        await asyncio.sleep(2)
6        return "done"
7    except asyncio.CancelledError:
8        print("task cancelled")
9        raise
10
11async def main():
12    task = asyncio.create_task(slow())
13    try:
14        print(await asyncio.wait_for(task, timeout=0.3))
15    except asyncio.TimeoutError:
16        task.cancel()
17        try:
18            await task
19        except asyncio.CancelledError:
20            print("cleaned up")
21
22asyncio.run(main())
OUTPUT
task cancelled cleaned up
FADE OUT
EXT. CLOSING SHOT - NIGHT
NARRATOR (V.O.)
Async Python isn't about squeezing raw milliseconds out of CPUs. it's about letting your characters share the stage without tripping on each other. When the plot is mostly waiting, let the dispatcher keep the market alive.
THE END
← more posts
share this post