Waiting for Stuff
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
- gotcha The `wait` function is a blocking operation. In asynchronous Python applications (e.g., using `asyncio`), directly calling `wait` will block the entire event loop, potentially freezing your application.
- gotcha By default, the `TimeoutExpired` exception provides a generic message. When dealing with complex waiting conditions, this can make debugging difficult.
- gotcha When using `ANY` or `ALL` with multiple predicates, the library's documentation notes that it does not call a predicate once it has been satisfied (for efficiency). If a predicate has side effects that are expected to occur on every poll, this behavior for `ANY`/`ALL` could be unexpected.
Install
-
pip install waiting
Imports
- wait
from waiting import wait
- TimeoutExpired
from waiting import wait, TimeoutExpired
- ANY
from waiting import wait, ANY
- ALL
from waiting import wait, ALL
Quickstart
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}")