timeout-sampler

raw JSON →
1.0.22 verified Mon Apr 27 auth: no python

A utility class that repeatedly calls a function until it returns a truthy value or a timeout expires. Provides customizable retry logic with sleep intervals. Version 1.0.22, actively maintained, monthly releases.

pip install timeout-sampler
error AttributeError: module 'timeout_sampler' has no attribute 'TimeoutSampler'
cause Installed incorrect package 'timeout-sampler-python' or similar name. The correct package is 'timeout-sampler'.
fix
pip uninstall timeout-sampler-python && pip install timeout-sampler
error TypeError: __init__() missing 1 required positional argument: 'exceptions_dict'
cause The 'exceptions_dict' parameter is mandatory in constructor.
fix
Add exceptions_dict={} or a dict with exception->bool mapping.
error StopIteration
cause The iterator raises StopIteration if timeout expires before any truthy value is returned. Usually handled by catching TimeoutExpiredError.
fix
Wrap iteration in try/except TimeoutExpiredError.
gotcha Iteration does not stop on first truthy value automatically; you must break yourself or use a loop with break. The iterator yields all results until timeout unless you break early.
fix Break out of the for loop once condition is met.
gotcha The 'exceptions_dict' parameter is required if you want to retry on exceptions; if omitted or empty, the sampler will not catch exceptions and they will propagate immediately.
fix Pass a dictionary mapping exception types to booleans (True to retry, False to raise) or an empty dict {} to avoid retry on any exception.
deprecated Import from 'timeout_sampler' directly is the only supported path. Some older examples incorrectly import from submodules like 'timeout_sampler.timeout_sampler'.
fix Use 'from timeout_sampler import TimeoutSampler'.

Basic usage showing how to wait for a function to return a truthy value.

from timeout_sampler import TimeoutSampler
import time

def sample_func():
    return None  # simulate condition not ready

# Wait up to 5 seconds, check every 0.5 seconds
sampler = TimeoutSampler(
    timeout=5,
    sleep=0.5,
    func=sample_func,
    exceptions_dict={}
)
try:
    for value in sampler:
        if value:
            print("Condition met")
            break
except TimeoutExpiredError:
    print("Timeout reached")