[Python Decorators] Throttle

By hientd, at: 2023年10月10日12:00

Estimated Reading Time: 2 min read

[Python Decorators] Throttle
[Python Decorators] Throttle

Managing Function Call Frequency with the Throttle Decorator


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

  1. @throttle(seconds): This decorator limits function calls to once every specified number of seconds.
     
  2. 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:


Related

Great Sites Website Review

[Useful Site Review] killedby.tech

Read more
AI Great Sites

[Useful Site Review] AI Trends

Read more
Subscribe

Subscribe to our newsletter and never miss out lastest news.