Skip to content

Instantly share code, notes, and snippets.

@saulshanabrook
Created July 24, 2014 18:17
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 saulshanabrook/e62a5669fe6fb87220d6 to your computer and use it in GitHub Desktop.
Save saulshanabrook/e62a5669fe6fb87220d6 to your computer and use it in GitHub Desktop.
recursive persistent memoization with python
import shelve
import functools
def cache(filename):
def decorating_function(user_function):
def wrapper(*args, **kwds):
key = str(hash(functools._make_key(args, kwds, typed=False)))
if not hasattr(cache, '_shelve'):
cache._shelve = shelve.open(filename, writeback=True)
should_close_shelve = True
else:
should_close_shelve = False
try:
return cache._shelve[key]
except KeyError:
result = user_function(*args, **kwds)
cache._shelve[key] = result
return result
if should_close_shelve:
self._shelve.close()
del self._shelve
else:
self._shelve.sync()
return functools.update_wrapper(wrapper, user_function)
return decorating_function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment