Skip to content

Instantly share code, notes, and snippets.

@ColinShark
Forked from gregburek/rateLimitDecorator.py
Last active February 20, 2022 00:08
Show Gist options
  • Save ColinShark/00caccb9d29e41090bf5c2d0a61e3dc5 to your computer and use it in GitHub Desktop.
Save ColinShark/00caccb9d29e41090bf5c2d0a61e3dc5 to your computer and use it in GitHub Desktop.
Rate limiting function calls with Python Decorators [Py3]
import time
def rate_limit(max_per_second=2):
min_interval = 1.0 / float(max_per_second)
def decorate(func):
last_time_called = [0.0]
def rate_limited_func(*args, **kargs):
elapsed = time.process_time() - last_time_called[0]
left_to_wait = min_interval - elapsed
if left_to_wait > 0:
time.sleep(left_to_wait)
ret = func(*args, **kargs)
last_time_called[0] = time.process_time()
return ret
return rate_limited_func
return decorate
@rate_limit(2) # 2 per second at most
def PrintNumber(num):
print(num)
if __name__ == "__main__":
print("This should print 1,2,3... at about 2 per second.")
for i in range(1, 100):
PrintNumber(i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment