×

python · level 3 · unit 5 · lesson 4

  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

Set a so one slow reply never hangs your program.

Real services are sometimes slow or broken. waits at most half a second. If the coroutine is not done by then, it is cancelled and you get a , which you can catch like any other error.

With gather, one failing coroutine normally raises its error and you lose every result. Pass return_exceptions=True and each failure comes back as an error object in the results list instead, next to the successes.

import asyncio

async def slow_reply():
    await asyncio.sleep(1)
    return "finally!"

async def main():
    try:
        reply = await asyncio.wait_for(slow_reply(), timeout=0.1)
        print(reply)
    except TimeoutError:
        print("Gave up after 0.1 seconds. Try again later.")

asyncio.run(main())

Before Python 3.11 this error was called asyncio.TimeoutError, so you may meet that name in older code.