The throttle decorator in Python is used to limit how frequently a function can be called. This is particularly useful for rate limiting to prevent a function from being called too often, which can be important for functions interacting with APIs or performing resource-intensive tasks.
NOTE: Django Rest Framework offers this feature internally
Implementation
Here's how you can implement a throttle decorator:
import time
from functools import wraps
def throttle(seconds):
def decorator(func):
last_called = [0]
@wraps(func)
def wrapper(*args, **kwargs):
elapsed = time.time() - last_called[0]
if elapsed >= seconds:
last_called[0] = time.time()
return func(*args, **kwargs)
else:
print("Function call throttled")
return wrapper
return decorator
@throttle(5)
def my_function():
print("Function called")
my_function() # Output: Function called
time.sleep(2)
my_function() # Output: Function call throttled
time.sleep(5)
my_function() # Output: Function called
Explanation
- @throttle(seconds): This decorator limits function calls to once every specified number of seconds.
- last_called: Tracks the last time the function was called to enforce the throttle.
Benefits
- Rate Limiting: Prevents functions from being called too frequently, protecting resources.
- Control: Ensures that resource-intensive functions do not overload the system.
Use Cases
- API Requests: Limit the rate of requests to comply with API rate limits.
- Resource Management: Control access to functions that perform heavy computations or database operations.
Conclusion
The throttle decorator is a valuable tool for managing the frequency of function calls, ensuring your application remains efficient and compliant with rate limits.
You can find more Python decorators here:
![[Python Decorators] Throttle](/_next/image?url=https%3A%2F%2Fapi.cms.glinteco.com%2Fuploads%2Flarge_python_decorators_throttle_c62466f971.png&w=3840&q=100)

![[One Package Per Day] Poetry: Deterministic Dependency Management](/_next/image?url=https%3A%2F%2Fapi.cms.glinteco.com%2Fuploads%2Flarge_one_package_per_day_poetry_deterministic_dependency_management_6c0e1efe35.jpg&w=3840&q=75)
