Skip to content

Instantly share code, notes, and snippets.

@romanbsd
Created July 27, 2023 14:47
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 romanbsd/f23ed75ae56f04db5ec45965b5a50d28 to your computer and use it in GitHub Desktop.
Save romanbsd/f23ed75ae56f04db5ec45965b5a50d28 to your computer and use it in GitHub Desktop.
import pickle
import os
def cache_to_pickle(cache_dir):
def decorator(func):
def wrapper(*args, **kwargs):
# Generate a unique cache filename based on the function and its arguments
cache_filename = f"{func.__name__}_{hash((args, tuple(kwargs.items())))}.pickle"
cache_path = os.path.join(cache_dir, cache_filename)
if os.path.exists(cache_path):
# If the cached result exists, load and return it
with open(cache_path, 'rb') as cache_file:
return pickle.load(cache_file)
else:
# If the cached result doesn't exist, compute the result and cache it
result = func(*args, **kwargs)
with open(cache_path, 'wb') as cache_file:
pickle.dump(result, cache_file)
return result
return wrapper
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment