Ratelim
Ratelim is a simple Python library (version 0.1.6, last released Feb 2015) that provides decorators to limit the number of times a function can be called within a specific time interval. It's particularly useful for respecting rate limits of external APIs. It supports both greedy and patient rate limiting strategies and preserves the function signature. This library has not been updated since 2015.
Warnings
- deprecated The `ratelim` library has not been updated since February 2015. For new projects or applications requiring active maintenance, newer and more robust rate-limiting libraries (e.g., `pyrate-limiter`, `tomasbasham/ratelimit`) are recommended.
- gotcha By default, when a rate limit is exceeded, `ratelim` raises a `RateLimitException` immediately. It does not automatically wait or retry. Users must implement their own `try-except` block and `time.sleep` (or equivalent for async) to handle waiting and retrying.
- gotcha The `ratelim` library uses in-memory counters, making it unsuitable for distributed systems or multi-process applications where rate limits need to be coordinated across multiple instances or processes.
Install
-
pip install ratelim
Imports
- rate_limited
from ratelim import rate_limited
- RateLimitException
from ratelim import RateLimitException
Quickstart
import time
from ratelim import rate_limited, RateLimitException
n_calls = 5
n_seconds = 10
@rate_limited(calls=n_calls, period=n_seconds)
def limited_function():
print(f"Calling limited_function at {time.time()}")
print(f"Attempting to call limited_function {n_calls + 2} times over {n_seconds} seconds...")
for i in range(n_calls + 2):
try:
limited_function()
except RateLimitException:
print(f"Rate limit exceeded for call {i+1}! Sleeping for {n_seconds} seconds...")
time.sleep(n_seconds) # Manually handle retry logic
limited_function() # Retry after sleeping