Created
July 27, 2023 14:47
-
-
Save romanbsd/f23ed75ae56f04db5ec45965b5a50d28 to your computer and use it in GitHub Desktop.
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 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