paper_hashtag_federation/instance_scanner/picklecache.py

28 lines
1.0 KiB
Python

from functools import wraps
import pickle
import os
def cache_return(func):
"""caches the return value of a function locally as a pickle file"""
@wraps(func)
def wrapped(*args, **kwargs):
CACHEDIR = "__picklecache__"
if not os.path.exists(CACHEDIR):
os.mkdir(CACHEDIR)
cachefilename = "{}{}{}.pickle".format(func.__name__, args, kwargs)
# if cached serialization exists, comparereturn it
if os.path.exists(os.path.join(CACHEDIR, cachefilename)):
with open(os.path.join(CACHEDIR, cachefilename), "rb") as loadfile:
t = pickle.load(loadfile)
if args == t[0] and kwargs == t[1]:
return t[2]
# otherwise call function and serialize its return value
with open(os.path.join(CACHEDIR, cachefilename), "wb") as dumpfile:
funcreturn = func(*args, **kwargs)
t = (args, kwargs, funcreturn)
pickle.dump(t, dumpfile)
return funcreturn
return wrapped