Created
October 12, 2018 16:46
-
-
Save Susensio/975de273a2ad154a63e207e8336784a6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
from functools import wraps | |
def persistent_cache(cache_file='.cache'): | |
"""Using shelve module creates a cache that persists across executions. | |
Depends on repr giving a univocal representation of input arguments. | |
""" | |
def decorator(func): | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
with shelve.open(cache_file) as db: | |
key = f'{func.__module__}.{func.__qualname__}(*{repr(args)}, **{repr(kwargs)})' | |
try: | |
return db[key] | |
except KeyError: | |
result = func(*args, **kwargs) | |
db[key] = result | |
return result | |
return wrapper | |
return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment