Created
March 18, 2016 10:55
-
-
Save Ogreman/ea13655600c41c3b4816 to your computer and use it in GitHub Desktop.
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 datetime | |
def timed_cached(timeout=60 * 60, now=datetime.datetime.now): | |
def outer(method_or_attribute): | |
if not hasattr(timed_cached, '__mapping'): | |
timed_cached.__mapping = {} | |
if not hasattr(timed_cached, 'flush'): | |
timed_cached.flush = lambda: timed_cached.__mapping.clear() | |
def wrapped(*args, **kwargs): | |
time_now = now() | |
cache = timed_cached.__mapping.setdefault(str(method_or_attribute) + str(args) + str(kwargs), {}) | |
invalid = time_now > cache.get('__last_cache', time_now) + datetime.timedelta(seconds=timeout) | |
if ('__cache' not in cache) or ('__last_cache' not in cache) or invalid: | |
if '__cache' in cache: | |
del cache['__cache'] | |
cache['__cache'] = method_or_attribute(*args, **kwargs) | |
cache['__last_cache'] = time_now | |
return cache['__cache'] | |
return wrapped | |
return outer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment