import time
import functools


def ratelimit(reqs_per_second):
    """Make sure the decorated function is rate-limited.

    Inserts delays to ensure the decorated function gets called not more than
    reqs_per_second times per second.
    """
    interval = 1.0 / reqs_per_second
    next_window = time.time()

    def _ratelimit(fn):
        @functools.wraps(fn)
        def _wrapper(*args, **kw):
            nonlocal next_window
            now = time.time()
            if now < next_window:
                time.sleep(next_window - now)
                next_window += interval
            else:
                next_window = now + interval
            return fn(*args, **kw)
        return _wrapper

    return _ratelimit