Skip to main content

Debounce and throttle decorators for Python functions.

Project description

philiprehberger-debounce

Tests PyPI version Last updated

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

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).
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.4.0.tar.gz (7.8 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.4.0-py3-none-any.whl (6.0 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: philiprehberger_debounce-0.4.0.tar.gz
  • Upload date:
  • Size: 7.8 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.4.0.tar.gz
Algorithm Hash digest
SHA256 280e559611ddf9a9f54ecf2372a645b4b8953a8dcb5cbf9127dfee25bfa7719c
MD5 6fef3914a279e83b88b52e5e4af956eb
BLAKE2b-256 a65f60f3b2c18e2919cdf84915fe6dc8b63203943cf3c4dbe58e9eb4e91d0ef4

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for philiprehberger_debounce-0.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5778130452df2aab7a27072c1ca7c15bbe9f3ce8d8488e07acf693b190109c4a
MD5 c9dba09cb5431a342a6bad050049b85f
BLAKE2b-256 665e8e4cbccff808330320f71e2c8c16709b845acc670609aeb6771f82cf3ecf

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