Skip to content

Instantly share code, notes, and snippets.

@jakab922
Last active July 5, 2018 11:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakab922/6610714 to your computer and use it in GitHub Desktop.
Save jakab922/6610714 to your computer and use it in GitHub Desktop.
Caching decorator with timeout. Might not be good for class instance/class methods.
from functools import wraps
from json import dumps
from datetime import datetime
def timeout_cache(max_timeout):
def timeout_cache_inner(fn):
fn._cache = {}
fn._timeout = max_timeout
@wraps(fn)
def cached(*args, **kwargs):
key = "%s - %s" % (
dumps(args), dumps(kwargs))
cache, timeout = fn._cache, fn._timeout
now = datetime.now()
if key not in cache or
now - cache[key]["time"] > timeout:
value = fn(*args, **kwargs)
cache[key] = {
"time": now,
"value": value
}
return cache[key]["value"]
return cached
return timeout_cache_inner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment