Skip to main content

Debounce and throttle decorators for Python functions.

Project description

philiprehberger-debounce

Tests PyPI version Last updated

philiprehberger-debounce

Debounce and throttle decorators for Python functions.

Installation

pip install philiprehberger-debounce

Usage

from philiprehberger_debounce import debounce, throttle

Debounce

Delay execution until a quiet period has passed. Each new call resets the timer.

@debounce(0.5)
def on_resize(width, height):
    print(f"Resized to {width}x{height}")

on_resize(800, 600)
on_resize(1024, 768)  # cancels the previous call
# Only the last call executes after 0.5s

Bounded debounce

Use max_wait to guarantee the function fires at most max_wait seconds after the first pending call, even if calls keep arriving and continuously reset the debounce timer. Mirrors lodash debounce({ maxWait }) semantics.

@debounce(0.5, max_wait=2.0)
def autosave(content):
    print(f"Saving: {content[:20]}...")

# Even with continuous edits, autosave fires at least every 2s.
for chunk in stream_keystrokes():
    autosave(chunk)

max_wait must be positive and >= seconds; otherwise ValueError is raised.

Cancel and flush

The wrapper exposes .cancel() (drop any pending trailing call) and .flush() (fire it immediately). Mirrors the lodash debounce control API.

@debounce(0.5)
def save(content):
    print(f"saving {content}")

save("draft 1")
save.cancel()       # drop the pending call
save("draft 2")
save.flush()        # fire immediately, don't wait for the timer

Pending check

.is_pending() returns whether a trailing call is queued — useful for showing "Saving…" indicators or guarding code paths that depend on whether the debounced action will still fire.

@debounce(0.5)
def save(content):
    ...

save("draft 1")
if save.is_pending():
    show("Saving…")

Throttle

Limit a function to a fixed number of calls within a time window. Excess calls are silently dropped.

@throttle(calls=3, per=1.0)
def send_request(data):
    print(f"Sending {data}")

for i in range(10):
    send_request(i)  # only the first 3 calls within 1s execute

API

Decorator Parameter Description
debounce(seconds, *, leading=False, max_wait=None) seconds Minimum quiet period (in seconds) before the function is invoked. Each new call cancels the previous pending invocation and restarts the timer.
leading If True, fire on the leading edge of the window instead of the trailing edge. Subsequent rapid calls are suppressed until seconds of silence have elapsed.
max_wait Optional upper bound (in seconds) on how long the function may be deferred from the first pending call. Must be positive and >= seconds. Mirrors lodash debounce({ maxWait }).
wrapper.cancel() Discard any pending trailing invocation and reset leading-edge state.
wrapper.flush() Fire the pending trailing invocation immediately (no-op if none is pending).
wrapper.is_pending() Return True if a trailing call is queued and not yet fired.
throttle(calls, per) calls Maximum number of allowed invocations within the sliding window.
per Length of the sliding window in seconds. Calls beyond calls within per are silently dropped.

Development

pip install -e .
python -m pytest tests/ -v

Support

If you find this project useful:

Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

philiprehberger_debounce-0.5.0.tar.gz (182.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

philiprehberger_debounce-0.5.0-py3-none-any.whl (6.2 kB view details)

Uploaded Python 3

File details

Details for the file philiprehberger_debounce-0.5.0.tar.gz.

File metadata

  • Download URL: philiprehberger_debounce-0.5.0.tar.gz
  • Upload date:
  • Size: 182.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.13

File hashes

Hashes for philiprehberger_debounce-0.5.0.tar.gz
Algorithm Hash digest
SHA256 6a532fdd2945448ec9d5855092f74a1f9df366c5d56a2a335d3d45b5098d6d3d
MD5 b81e68271b6cf77bc5ce808aca242cd1
BLAKE2b-256 f19e3cd434c79423d1d419baf9a2399d1f10e90a3bfaa86417fb502d783e1021

See more details on using hashes here.

File details

Details for the file philiprehberger_debounce-0.5.0-py3-none-any.whl.

File metadata

File hashes

Hashes for philiprehberger_debounce-0.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 bf21741db806322c5e43309a1482bf9fdc674b59fee2997f5e9fe3c816295bad
MD5 488166c5412f1155b8e898535958bed0
BLAKE2b-256 4e55925405a7f616b45ce9c8a79644685cd8d2bf78a947de30240452e40cd81e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page