Skip to content

Instantly share code, notes, and snippets.

@SLAPaper
Forked from ChrisTM/throttle.py
Last active April 9, 2019 18:22
Show Gist options
  • Select an option

  • Save SLAPaper/9ef3699e5f76dc80c00bd2d405eef995 to your computer and use it in GitHub Desktop.

Select an option

Save SLAPaper/9ef3699e5f76dc80c00bd2d405eef995 to your computer and use it in GitHub Desktop.
Python decorator for throttling function calls.
# https://gist.github.com/SLAPaper/9ef3699e5f76dc80c00bd2d405eef995
from datetime import datetime, timedelta
from functools import wraps
class throttle:
"""
Decorator that prevents a function from being called more than once every
time period.
To create a function that cannot be called more than once a minute:
@throttle(minutes=1)
def my_fun():
pass
"""
def __init__(self, *args, **kwargs):
self.throttle_period = timedelta(*args, **kwargs)
self.time_of_last_call = datetime.min
def __call__(self, fn):
@wraps(fn)
def wrapper(*args, **kwargs):
now = datetime.now()
time_since_last_call = now - self.time_of_last_call
if time_since_last_call > self.throttle_period:
self.time_of_last_call = now
return fn(*args, **kwargs)
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment