brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's asyncio.timeout puts a time limit on a block of awaits

Python
~/tips/tip-python-asyncio-timeout-context-manager

import asyncio

Wrap awaits in asyncio.timeout and get a TimeoutError when the time is up.

Putting a deadline on a whole piece of async code used to mean wrapping a single coroutine in asyncio.wait_for. Since Python 3.11 there is asyncio.timeout, a context manager that covers everything inside the block.

import asyncio

async def slow():
    await asyncio.sleep(5)

async def main():
    try:
        async with asyncio.timeout(0.5):
            await slow()
    except TimeoutError:
        print("gave up after 0.5s")

asyncio.run(main())

It printed gave up after 0.5s right away. When the time is up, the block is cancelled and the cancellation turns into a normal TimeoutError outside it. Several awaits in the block share one budget, which is the nice part.

Passing None as the delay means no limit, so you can make the timeout configurable. From Python 3.11 on, asyncio.TimeoutError is the same class as the built-in TimeoutError, so the short name is enough.

The caveat: cancellation only lands at an await. If the block calls blocking code such as time.sleep(1), nothing can interrupt it. A 0.2 second timeout around a one second time.sleep raised no error, and the script just took the full second.

The object returned by async with asyncio.timeout(...) as cm has an expired() method. In a quick check it returned False inside the block and True after a one second timeout fired, which helps when you want to tell your own timeout from a TimeoutError raised by something deeper in the call. The same object has reschedule() to move the deadline.

Further reading: asyncio.timeout

More Python tips from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 from functools import cached_property All Python tips (107) All topics

Link