Ratelimiter
The `ratelimiter` library provides a simple mechanism for rate-limiting operations in Python, both synchronously (using decorators or context managers) and asynchronously (using `async with`). It allows developers to control the frequency of function calls, often useful when interacting with APIs that have usage limits. The current version is 1.2.0.post0, and the project has not seen updates since 2017, suggesting it is no longer actively maintained.
Warnings
- deprecated The `ratelimiter` library has not been updated since December 2017. While it may still function, it is not actively maintained, meaning it might not receive bug fixes, security patches, or compatibility updates for newer Python versions or evolving best practices. Consider more actively maintained alternatives like `pyrate-limiter` or `limits` for new projects.
- gotcha The behavior of callbacks differs between synchronous and asynchronous usage. For synchronous decorators/context managers, the `callback` function is executed in a *separate thread*, allowing it to `sleep` without blocking the main program. For `async with` usage, the `callback` must be a *coroutine* and is *not* called in a a separate thread.
- gotcha This library is designed for in-process rate limiting. It does not inherently support distributed rate limiting across multiple processes or machines without additional external coordination (e.g., a shared Redis backend). Using it directly in a distributed system will lead to each process having its own independent rate limit.
Install
-
pip install ratelimiter
Imports
- RateLimiter
from ratelimiter import RateLimiter
Quickstart
import time
from ratelimiter import RateLimiter
def limited_function():
print(f"Function called at {time.time()}")
def callback_function(until):
duration = int(round(until - time.time()))
print(f'Rate limited, sleeping for {duration} seconds')
# Using as a decorator
@RateLimiter(max_calls=2, period=3, callback=callback_function)
def do_something_decorated(item):
print(f"Processing item {item} (decorated)")
print("--- Decorator Example ---")
for i in range(5):
do_something_decorated(i)
time.sleep(0.5) # Simulate some work between calls
# Using as a context manager
rate_limiter_cm = RateLimiter(max_calls=2, period=3, callback=callback_function)
print("\n--- Context Manager Example ---")
for i in range(5):
with rate_limiter_cm:
print(f"Processing item {i} (context manager)")
time.sleep(0.5) # Simulate some work between calls