Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

asyncio.timeout

Applies a deadline to awaits inside an asynchronous context manager.

Version: Python 3.14; repository image, production runtime not attested

Syntax

async with asyncio.timeout(delay) as deadline: ...

Applies a deadline to awaits inside an asynchronous context manager.

Timeout cancellation is translated to TimeoutError on leaving the context, so catch that exception outside the managed block.

Bound a block of awaits in the current task. delay is measured in seconds, and None leaves the deadline unset for later rescheduling. Expiry cancels the current task; as the cancellation leaves the scope the manager turns its own cancellation into TimeoutError, caught outside. A zero delay schedules expiry on the next loop turn.

import asyncio
async def main():
    async with asyncio.timeout(None) as deadline:
        assert deadline.when() is None and not deadline.expired()
        deadline.reschedule(asyncio.get_running_loop().time() + 5)
        await asyncio.sleep(0)
    try:
        async with asyncio.timeout(0) as immediate:
            await asyncio.Event().wait()
    except TimeoutError:
        assert immediate.expired()
asyncio.run(main())

Examples

import asyncio

async def main():
    try:
        async with asyncio.timeout(0):
            await asyncio.sleep(1)
    except TimeoutError as error:
        print(type(error).__name__)

asyncio.run(main())

Result

TimeoutError

Bound a block of awaits in the current task. delay is measured in seconds, and None leaves the deadline unset for later rescheduling. Expiry cancels the current task; as the cancellation leaves the scope the manager turns its own cancellation into TimeoutError, caught outside. A zero delay schedules expiry on the next loop turn.

Sources