Skip to content

Instantly share code, notes, and snippets.

@Ogreman
Created March 18, 2016 10:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ogreman/ea13655600c41c3b4816 to your computer and use it in GitHub Desktop.
Save Ogreman/ea13655600c41c3b4816 to your computer and use it in GitHub Desktop.
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