Dev Helpers

Python / Async workflows

Catch a timeout around a task

Dev Helpers · May 22, 2026

A timeout limits how long a caller waits and can cancel work inside its scope. Cleanup needs to survive cancellation.

Worked example

import asyncio
async def main():
    try:
        async with asyncio.timeout(0):
            await asyncio.sleep(1)
    except TimeoutError:
        print('Timed out')
asyncio.run(main())

Result

Timed out

Implementation notes

A timed-out task can have already performed part of its work. Make retried operations safe if a cancelled attempt may have changed external state.

Try it yourself

Try a task shorter than the deadline and one that exceeds it.

Open the Python example →

Editorial date May 22, 2026 · Published December 6, 2026

Related articles

Run an async function

An async function call creates a coroutine. A top-level runner supplies the event loop that executes it.

Transpose a matrix

Transposing rows into columns assumes a decision about uneven rows. Ordinary zip stops at the shortest input.

Unpack with a remainder

Starred unpacking separates a fixed header from a variable-length tail. It still requires enough elements for the fixed positions.