A decorator that caches the output DataFrame(s) of the decorated function in a directory. The directory is determined by hashing the arguments of the function call. If the cached output exists for given arguments, it is loaded from the file(s) instead of calling the function. The ar
(cache_dir: str, force: bool = False)
| 138 | |
| 139 | |
| 140 | def cache(cache_dir: str, force: bool = False): |
| 141 | """ |
| 142 | A decorator that caches the output DataFrame(s) of the decorated function in a directory. |
| 143 | The directory is determined by hashing the arguments of the function call. |
| 144 | If the cached output exists for given arguments, it is loaded from the file(s) instead of calling the function. |
| 145 | The arguments of the function are stored in a separate JSON file in the same directory. |
| 146 | """ |
| 147 | def actual_decorator(func): |
| 148 | @functools.wraps(func) |
| 149 | def wrapper(*args, **kwargs): |
| 150 | argument_hash = hash_args(*args, **kwargs) |
| 151 | dir_path = f"{cache_dir}/{argument_hash}" |
| 152 | |
| 153 | if not os.path.exists(dir_path): |
| 154 | os.makedirs(dir_path) |
| 155 | |
| 156 | arguments_file = f"{dir_path}/arguments.json" |
| 157 | |
| 158 | # Try to load cached data |
| 159 | output_dfs = [] |
| 160 | |
| 161 | if not force: |
| 162 | i = 0 |
| 163 | while os.path.exists(f"{dir_path}/dataframe{i}.feather"): |
| 164 | output_dfs.append(pd.read_feather(f"{dir_path}/dataframe{i}.feather")) |
| 165 | i += 1 |
| 166 | |
| 167 | if output_dfs: |
| 168 | # If any output was found, return it |
| 169 | print(f"Loaded cached data from {dir_path}") |
| 170 | if len(output_dfs) == 1: |
| 171 | return output_dfs[0] |
| 172 | return tuple(output_dfs) |
| 173 | else: |
| 174 | # If no output was found, call the function |
| 175 | output_dfs = func(*args, **kwargs) |
| 176 | |
| 177 | # Check that the function's return value is a DataFrame or tuple |
| 178 | if isinstance(output_dfs, pd.DataFrame): |
| 179 | output_dfs = (output_dfs,) # convert single dataframe to tuple |
| 180 | elif isinstance(output_dfs, tuple) and all(isinstance(df, pd.DataFrame) for df in output_dfs): |
| 181 | pass # all good, it's a tuple of DataFrames |
| 182 | else: |
| 183 | raise ValueError("Function must return a DataFrame or a tuple of DataFrames") |
| 184 | |
| 185 | # Cache the output data |
| 186 | print(f"Caching data to {dir_path}") |
| 187 | for i, output_df in enumerate(output_dfs): |
| 188 | output_df = output_df.reset_index(drop=True) |
| 189 | output_df.to_feather(f"{dir_path}/dataframe{i}.feather") |
| 190 | |
| 191 | # Cache the arguments |
| 192 | extended_json_dump({"args": list(args), "kwargs": kwargs}, arguments_file) |
| 193 | |
| 194 | if len(output_dfs) == 1: |
| 195 | return output_dfs[0] |
| 196 | return output_dfs |
| 197 |
nothing calls this directly
no outgoing calls
no test coverage detected