Registry / testing / polling

polling

JSON →
library0.3.2pypypi✓ verified 25d ago

The `polling` library provides a simple yet powerful utility to repeatedly call a function until a desired condition is met or a timeout occurs. It is useful for waiting on external resources, API responses, or file system changes. The latest version is 0.3.2, released in May 2021. While functional, it is considered to be in maintenance mode, with a more actively developed and recommended fork, `polling2`, available.

pip install polling
INSTALL
IMPORT
SIG · POLLING
P
polling
testingpythonv0.3.2
Install
2.4s avg
Import
10ms
Disk
17MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.3.2 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.004s · 19.2MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.4s · import 0.004s · 20MB
17MB installed
● package 17MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

poll
from polling import poll
import polling; polling.poll()
The primary function `poll` is usually imported directly for conciseness.
TimeoutException
from polling import TimeoutException
Used for catching timeout errors and inspecting intermediate values.

This quickstart demonstrates how to use `polling.poll` to wait for a simulated asynchronous task to complete. It shows how to define a success condition using `check_success`, set polling intervals with `step`, and handle timeouts with `TimeoutException`. An additional example illustrates how to `ignore_exceptions` during polling.

import time from polling import poll, TimeoutException def my_task_status(task_id): # Simulate an external task that eventually completes # In a real scenario, this would check a database, API, etc. statuses = {123: ['pending', 'processing', 'completed']} current_status_index = getattr(my_task_status, 'counter', 0) status_list = statuses.get(task_id, ['failed']) status = status_list[current_status_index % len(status_list)] my_task_status.counter = current_status_index + 1 print(f"Task {task_id}: current status is '{status}'") return status my_task_status.counter = 0 # Initialize counter try: # Poll until the task status is 'completed' or timeout after 5 seconds result = poll( lambda: my_task_status(123), check_success=lambda status: status == 'completed', step=1, # Check every 1 second timeout=5 # Stop after 5 seconds ) print(f"Task completed with status: {result}") except TimeoutException as te: print(f"Polling timed out after {te.timeout} seconds.") print(f"Last value before timeout: {te.values.get_nowait()}") # Reset counter for another run (optional) my_task_status.counter = 0 try: # Example with ignoring exceptions (e.g., during initial setup) # This dummy function will raise an error initially, then succeed def flaky_check(): if getattr(flaky_check, 'fail_count', 0) < 2: flaky_check.fail_count = getattr(flaky_check, 'fail_count', 0) + 1 raise ValueError("Still setting up...") return "Success!" flaky_check.fail_count = 0 result_ignored = poll( flaky_check, ignore_exceptions=(ValueError,), step=0.5, timeout=3 ) print(f"Flaky check succeeded: {result_ignored}") except TimeoutException: print("Flaky check timed out.")
Debug
Known issues
gotchaThe `polling` library (justiniso/polling) is no longer actively maintained. For ongoing development and better support, consider using the `polling2` library (ddmee/polling2), which is a direct fork and actively developed.
fix
Migrate to `polling2` by installing `pip install polling2` and changing imports from `polling` to `polling2`.
affects: 0.3.0 and above
gotchaUsing `poll_forever=True` without a robust `check_success` condition or an external termination mechanism can lead to infinite loops, consuming resources indefinitely.
fix
Always define a clear `timeout` parameter or ensure that your `check_success` lambda/function will eventually return a truthy value or that an external event can terminate the polling process.
affects: All
gotchaWhen `polling.poll` times out, it raises a `TimeoutException`. This exception includes a `values` attribute (a queue) containing all values returned by the target function that did not meet the `check_success` condition before the timeout.
fix
Catch `TimeoutException` and inspect `te.values` to debug why the condition was not met. Use `te.values.get_nowait()` or iterate the queue to access the collected values.
affects: All
Errors
Common errors & fixes
polling.TimeoutException
The polling operation exceeded the specified `timeout` duration or the `max_tries` limit before the `target` function returned a successful (truthy) value or met the `check_success` condition.
fix
Increase the `timeout` or `max_tries` parameters, or ensure the `target` function is expected to succeed within the given limits. Handle the exception gracefully using a `try-except` block.

```python
import polling
import time

def my_task():
    # Simulate a task that sometimes succeeds
    if time.time() % 5 < 1:  # Succeeds for 1 second every 5 seconds
        return True
    return False

try:
    polling.poll(lambda: my_task(), step=0.1, timeout=2)
    print("Task succeeded!")
except polling.TimeoutException as e:
    print(f"Polling timed out: {e}")
    # Access collected values, if any, from e.values
    # while not e.values.empty():
    #     print(e.values.get())
```
TypeError: poll() missing 2 required positional arguments: 'target' and 'step'
The `polling.poll()` function was called without providing the mandatory `target` function (the function to be polled) and the `step` interval (how often to poll).
fix
Always provide at least the `target` function and the `step` interval to `polling.poll()`.

```python
import polling
import time

def check_status():
    # Your condition check here
    return True

# Correct usage:
polling.poll(target=check_status, step=1, timeout=10)

# Incorrect usage (leads to error):
# polling.poll()
# polling.poll(target=check_status)
# polling.poll(step=1)
```
TypeError: 'PollingException' object is not iterable
This error occurs when attempting to iterate directly over a `polling.PollingException` or `polling.TimeoutException` object, likely in an `except` block. The exception object itself is not iterable; instead, the `values` attribute (a `queue.Queue` object) should be used to access collected values, if `collect_values` was enabled.
fix
If you intend to access the values collected during the polling attempts, access the `values` attribute of the `TimeoutException` object, which is a `queue.Queue` (or `collections.deque` in some versions/forks) and is iterable. Ensure `collect_values=True` was passed to `polling.poll()` if you want values to be collected.

```python
import polling
import random

try:
    polling.poll(lambda: random.choice([0, (), False]), step=0.5, timeout=1, collect_values=True)
except polling.TimeoutException as te:
    print("Polling timed out. Values that did not meet the condition:")
    # Correct way to access collected values
    while not te.values.empty():
        print(te.values.get())

# Incorrect way (leads to TypeError):
# except polling.TimeoutException as te:
#    for value in te: # This would cause the error
#        print(value)
```
Upgrade
Version history
0.3.2latest on PyPI · released May 22, 2021
Audit
Dependencies

No dependency data recorded yet.

Agent activity
34 hits · last 30 days
node
28
OpenAI (training)
1
Resources
polling — pip install polling · libregistry