Last active
February 3, 2023 20:38
-
-
Save jh0ker/56f5b4fb7d015b1b9e4c74d4a91d4568 to your computer and use it in GitHub Desktop.
Memoize-with-timeout decorator
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
#!/usr/bin/env python | |
# Source: http://code.activestate.com/recipes/325905-memoize-decorator-with-timeout/#c1 | |
import time | |
from functools import wraps | |
class MWT: | |
"""Memoize With Timeout""" | |
_caches = {} | |
_timeouts = {} | |
def __init__(self, timeout=2): | |
self.timeout = timeout | |
def collect(self): | |
"""Clear cache of results which have timed out""" | |
t = time.time() | |
for func in self._caches: | |
cache = {} | |
for key in self._caches[func]: | |
if (t - self._caches[func][key][1]) < self._timeouts[func]: | |
cache[key] = self._caches[func][key] | |
self._caches[func] = cache | |
def __call__(self, f): | |
cache = self._caches[f] = {} | |
self._timeouts[f] = self.timeout | |
@wraps(f) | |
def func(*args, **kwargs): | |
kw = sorted(kwargs.items()) | |
key = (args, tuple(kw)) | |
t = time.time() | |
try: | |
v = cache[key] | |
print("cache") | |
if (t - v[1]) > self.timeout: | |
raise KeyError | |
except KeyError: | |
print("new") | |
v = cache[key] = f(*args,**kwargs), t | |
return v[0] | |
def clear_cache(): | |
self._caches[f].clear() | |
func.clear_cache = clear_cache | |
return func |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Revision 2 has some formatting changes, it uses
functools.wraps
for better decorators, normalizes timestamps and most importantly adds aclear_cache
function to the decorated functions.