wait-for2 Asyncio Timeout Utility

0.4.1 · active · verified Thu Apr 16

wait-for2 provides an enhanced `asyncio.wait_for` function designed to robustly handle complex scenarios involving simultaneous task completion and cancellation. It aims to prevent race conditions where a task might complete just as it's being cancelled. The current version is 0.4.1. Releases are made on an as-needed basis, typically for bug fixes, Python version compatibility, or new features.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the basic usage of `wait_for2` with a timeout, and then showcases the `race_handler` callback, including its 2-argument signature introduced in v0.3.0. The `race_handler` allows custom logic for outcomes where a task either completes or times out/gets cancelled.

import asyncio
from wait_for2 import wait_for2

async def task_that_might_timeout():
    """A mock async task that takes some time to complete."""
    await asyncio.sleep(0.6)
    return "Task completed!"

async def main():
    print("--- Basic Timeout Example ---")
    try:
        # Attempt to run the task with a timeout shorter than its execution time
        result = await wait_for2(task_that_might_timeout(), timeout=0.5)
        print(f"Success: {result}")
    except asyncio.TimeoutError:
        print("Timeout: Task did not complete in time.")

    print("\n--- Race Handler Example (v0.3.0+ signature) ---")
    async def fast_task():
        await asyncio.sleep(0.1)
        return "Fast result"

    async def slow_task():
        await asyncio.sleep(1.0)
        return "Slow result"

    # Define a custom race handler that inspects the result and exception status
    async def custom_race_handler(result, is_exception):
        if is_exception:
            print(f"  Handler caught exception: {result.__class__.__name__}")
            return "Handled exception scenario"
        print(f"  Handler caught completion: {result}")
        return f"Handled: {result}"

    # Scenario 1: Task completes within timeout, handler gets completion result
    result_complete = await wait_for2(fast_task(), timeout=0.5, race_handler=custom_race_handler)
    print(f"  wait_for2 result (completion): {result_complete}")

    # Scenario 2: Task times out, handler gets TimeoutError
    result_timeout = await wait_for2(slow_task(), timeout=0.2, race_handler=custom_race_handler)
    print(f"  wait_for2 result (timeout): {result_timeout}")

if __name__ == "__main__":
    asyncio.run(main())

view raw JSON →