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
wait_forcancels the coroutine aftertimeout.- A
TimeoutErrorsignals it ran too long. - The handler returns a fallback instead.
Keywords and builtins used here
asyncawaitdefexceptmainreturnslow_querytry
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.
Step 3 of 4 in Async, step 26 of 53 in Pythonic Python.