Ratelim

0.1.6 · maintenance · verified Sat Apr 11

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

Install

Imports

Quickstart

This quickstart demonstrates how to use the `@rate_limited` decorator to restrict function calls. It also shows how to catch `RateLimitException` and implement basic retry logic, as `ratelim` itself does not provide built-in `sleep_and_retry` functionality.

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

view raw JSON →