Code

Timeouts & Cancellation

Never wait forever. Networks hang and sensors stall. Python 3.11+ gives you a timeout block:

try:
    async with asyncio.timeout(2):
        data = await fetch_map("Fog Isle")
except TimeoutError:
    data = None  # gave up after 2 seconds

(await asyncio.wait_for(coro, 2) does the same for a single awaitable.)

How cancellation works

When time runs out, asyncio cancels the work inside the block. It raises asyncio.CancelledError inside the coroutine, at the await where it is paused. That gives the coroutine a chance to clean up:

async def worker():
    try:
        await asyncio.sleep(10)
    finally:
        print("closing connection")  # always runs

You can also cancel a task yourself with task.cancel().

If you catch CancelledError, re-raise it after cleaning up. If you swallow it, asyncio can't tell the work was stopped, and timeouts stop working properly.

Assignment

Write fetch_or_default(coro, seconds, default):

  1. Await coro, but give up after seconds seconds.
  2. If it finishes in time, return its result.
  3. If it times out, return default. (The beacon will log that it was cancelled.)