Waiting for Stuff

1.5.0 · active · verified Sat Apr 11

The 'waiting' library provides a simple utility for busy-waiting, where the program pauses execution until a specified predicate function returns `True`. It supports various modes, including timeouts, custom sleep intervals, exponential backoff, and aggregation of multiple predicates (ANY/ALL). The current version is 1.5.0, released in August 2024, with a sporadic but recently updated release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the core `wait` function, showing how to wait for a predicate to become true, handling timeouts, and customizing polling intervals. It also highlights the benefit of the `waiting_for` argument for clearer error messages.

import time
from waiting import wait, TimeoutExpired

def check_condition():
    # Simulate a condition that eventually becomes true
    if not hasattr(check_condition, 'counter'):
        check_condition.counter = 0
    check_condition.counter += 1
    print(f"Checking condition (attempt {check_condition.counter})...")
    return check_condition.counter >= 3

print("Starting to wait...")
try:
    # Wait for the condition for a maximum of 5 seconds, polling every 0.5 seconds
    # Use 'waiting_for' for more descriptive timeout messages
    result = wait(
        check_condition,
        timeout_seconds=5,
        sleep_seconds=0.5,
        waiting_for="the counter to reach 3"
    )
    print(f"Condition met! Result: {result}")
except TimeoutExpired as e:
    print(f"Wait timed out: {e}")

print("--- Demonstrating TimeoutExpired without waiting_for ---")
try:
    wait(lambda: False, timeout_seconds=0.1)
except TimeoutExpired as e:
    print(f"TimeoutExpired message (less descriptive): {e}")

view raw JSON →