typestar

async timeouts in Python

Bounding how long an await is allowed to take.

import asyncio


async def slow_query():
    await asyncio.sleep(10)
    return "rows"


async def main():
    try:
        return await asyncio.wait_for(slow_query(), timeout=0.2)
    except TimeoutError:
        return "gave up"


outcome = asyncio.run(main())

How it works

  1. wait_for cancels the coroutine after timeout.
  2. A TimeoutError signals it ran too long.
  3. The handler returns a fallback instead.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
230
Tokens
58
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 33 seconds.

Type this snippet

Step 3 of 4 in Async, step 26 of 53 in Pythonic Python.

← Previous Next →