Created
February 26, 2014 05:29
-
-
Save siteshen/9224024 to your computer and use it in GitHub Desktop.
A cache decorator class with time-to-live support.
This file contains hidden or 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 functools | |
| import time | |
| def hash_object(obj): | |
| if isinstance(obj, (tuple, list)): | |
| return (type(obj), tuple([hash_object(it) for it in obj])) | |
| elif isinstance(obj, dict): | |
| return (type(obj), tuple([(k, hash_object(v)) | |
| for (k, v) in obj.iteritems()])) | |
| else: | |
| return obj | |
| # https://wiki.python.org/moin/PythonDecoratorLibrary#Cached_Properties | |
| class Cached(object): | |
| def __init__(self, ttl=300): | |
| self.ttl = ttl | |
| self._cache = {} | |
| def __call__(self, fn, *args, **kwargs): | |
| @functools.wraps(fn) | |
| def decorated(*args, **kwargs): | |
| # TODO: a better hash function? | |
| key = hash_object((args, kwargs)) | |
| now = time.time() | |
| try: | |
| value, last_update = self._cache[key] | |
| if self.ttl > 0 and now - last_update > self.ttl: | |
| raise AttributeError | |
| except (KeyError, AttributeError): | |
| value = fn(*args, **kwargs) | |
| self._cache[key] = (value, now) | |
| return value | |
| return decorated |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment