Created
July 24, 2014 18:17
-
-
Save saulshanabrook/e62a5669fe6fb87220d6 to your computer and use it in GitHub Desktop.
recursive persistent memoization with python
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
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