Skip to content

Instantly share code, notes, and snippets.

@rootux
Forked from jh0ker/mwt.py
Last active June 12, 2018 11:50
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 rootux/06d1a63ce6038645c9cad4d3dc416027 to your computer and use it in GitHub Desktop.
Save rootux/06d1a63ce6038645c9cad4d3dc416027 to your computer and use it in GitHub Desktop.
Memoize-with-timeout decorator
#!/usr/bin/env python
# Source: http://code.activestate.com/recipes/325905-memoize-decorator-with-timeout/#c1
import time
class MWT(object):
"""Memoize With Timeout"""
_caches = {}
_timeouts = {}
def __init__(self,timeout=2):
self.timeout = timeout
def collect(self):
"""Clear cache of results which have timed out"""
for func in self._caches:
cache = {}
for key in self._caches[func]:
if (time.time() - self._caches[func][key][1]) < self._timeouts[func]:
cache[key] = self._caches[func][key]
self._caches[func] = cache
def __call__(self, f):
self.cache = self._caches[f] = {}
self._timeouts[f] = self.timeout
def func(*args, **kwargs):
kw = sorted(kwargs.items())
key = (args, tuple(kw))
try:
v = self.cache[key]
if (time.time() - v[1]) > self.timeout:
raise KeyError
except KeyError:
v = self.cache[key] = f(*args,**kwargs),time.time()
return v[0]
func.func_name = f.__name__
return func
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment