Created
March 3, 2011 20:07
-
-
Save ieure/853418 to your computer and use it in GitHub Desktop.
Example of a class which can be used as a decorator or context manager.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
from functools import wraps | |
class throttle(object): | |
"""Throttle calls to a method by `factor'.""" | |
def __init__(self, factor, error_only=False): | |
self.factor = factor | |
self.error_only = error_only | |
self.start_time = None | |
def __enter__(self): | |
"""Enter the nested context.""" | |
self.start_time = time.time() | |
def __exit__(self, type, value, traceback): | |
"""Exit the nested context.""" | |
if not self.error_only or (self.error_only and type): | |
time.sleep(self.factor * (time.time() - self.start_time)) | |
return False | |
def __call__(self, function): | |
"""Act as a decorator.""" | |
@wraps(function) | |
def __inner__(*args, **kwargs): | |
with self: | |
return function(*args, **kwargs) | |
return __inner__ | |
@throttle(2) | |
def test_one(): | |
print "I will be throttled for 2s." | |
time.sleep(1) | |
def test_two(): | |
with throttle(2): | |
print "I will be throttled for 2s." | |
time.sleep(1) | |
if __name__ == '__main__': | |
s = time.time() | |
test_one() | |
print time.time() - s | |
s = time.time() | |
test_two() | |
print time.time() - s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment