"""Data saving utilities with pickle."""# Created by Wenjie Du <wenjay.du@gmail.com># License: BSD-3-Clauseimportpickleimportpandasaspdfrom...utils.fileimportextract_parent_dir,create_dir_if_not_existfrom...utils.loggingimportlogger
[docs]defpickle_dump(data:object,path:str)->None:"""Pickle the given object. Parameters ---------- data: The object to be pickled. path: Saving path. Returns ------- `path` if succeed else None """try:# help create the parent dir if not existcreate_dir_if_not_exist(extract_parent_dir(path))withopen(path,"wb")asf:pickle.dump(data,f,protocol=pickle.HIGHEST_PROTOCOL)logger.info(f"Successfully saved to {path}")exceptExceptionase:logger.error(f"❌ Pickling failed. No cache data saved. Investigate the error below:\n{e}")returnNone
[docs]defpickle_load(path:str)->object:"""Load pickled object from file. Parameters ---------- path : Local path of the pickled object. Returns ------- Object Pickled object. """try:withopen(path,"rb")asf:ifpd.__version__>="2.0.0":data=pd.read_pickle(f)else:data=pickle.load(f)exceptExceptionase:logger.error(f"❌ Loading data failed. Operation aborted. Investigate the error below:\n{e}")returnNonereturndata