Skip to content

Instantly share code, notes, and snippets.

@Susensio
Created October 12, 2018 16:46
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 Susensio/975de273a2ad154a63e207e8336784a6 to your computer and use it in GitHub Desktop.
Save Susensio/975de273a2ad154a63e207e8336784a6 to your computer and use it in GitHub Desktop.
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