import functools
import time


def _rate_limit(func=None, per_second=1):
    """Limit number of requests made per second.

    Will sleep for 1/``per_second`` seconds if the last request was
    made too recently.
    """
    if not func:
        return functools.partial(_rate_limit, per_second=per_second)

    @functools.wraps(func)
    def wrapper(self, url, *args, **kwargs):
        if self.last_request is not None:
            now = time.time()
            delta = now - self.last_request
            if delta < (1 / per_second):
                time.sleep(1 - delta)

        self.last_request = time.time()
        return func(self, url, *args, **kwargs)

    return wrapper