Skip to main content

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

Release files for philiprehberger-debounce 0.5.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for philiprehberger-debounce 0.5.0
File Size Uploaded
philiprehberger_debounce-0.5.0.tar.gz 182.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for philiprehberger-debounce 0.5.0
File Interpreter ABI Platform
philiprehberger_debounce-0.5.0-py3-none-any.whl Python 3 none any Details

Total release size: 188.3 kB

Release files / philiprehberger_debounce-0.5.0.tar.gz

Download URL philiprehberger_debounce-0.5.0.tar.gz
Size 182.1 kB
Tags Source
SHA-256 checksum
How to use checksums
6a532fdd2945448ec9d5855092f74a1f9df366c5d56a2a335d3d45b5098d6d3d
BLAKE2b-256 checksum
How to use checksums
f19e3cd434c79423d1d419baf9a2399d1f10e90a3bfaa86417fb502d783e1021
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.13

Release files / philiprehberger_debounce-0.5.0-py3-none-any.whl

Download URL philiprehberger_debounce-0.5.0-py3-none-any.whl
Size 6.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
bf21741db806322c5e43309a1482bf9fdc674b59fee2997f5e9fe3c816295bad
BLAKE2b-256 checksum
How to use checksums
4e55925405a7f616b45ce9c8a79644685cd8d2bf78a947de30240452e40cd81e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.13

Release history Release notifications | RSS feed

This release

0.5.0 This release

2 release files

0.4.0

2 release files

0.3.0

2 release files

0.2.0

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page