Skip to content

Instantly share code, notes, and snippets.

@mccutchen
Last active November 25, 2015 17:11
Show Gist options
  • Select an option

  • Save mccutchen/80116aeeabeb71e6e582 to your computer and use it in GitHub Desktop.

Select an option

Save mccutchen/80116aeeabeb71e6e582 to your computer and use it in GitHub Desktop.
Simple in-memory cache decorator with TTL
def cached(ttl, cache={}):
"""
A decorator for nullary functions that caches their results in memory for a
given number of seconds.
"""
def cached_decorator(f):
key = f.__name__
def decorated(*args, **kwargs):
if key in cache:
result, ts = cache[key]
if time.now() - ts < ttl:
return result
result = f(*args, **kwargs)
cache[key] = (result, time.now())
return result
return decorated
return cached
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment