This Python package provides a simple decorator that allows you to cache the outputs of function calls to disk.
- Evaluate an expensive function once.
- Store its output on disk.
- Whenever the function is called again, retrieve the cached output from disk instead of evaluating it again.
- Simple to use: Apply a single decorator to your function to enable powerful caching
- Native file formats: The outputs of functions are serialized to disk using native file formats.
- For example,
numpyarrays are saved as.npyfiles. - As a fallback, function outputs can be saved as generic
picklefiles (.pkl).
- For example,
- Parameterizable: The filepaths where function outputs are saved can be parameterized by the function arguments.
- For example, when
add(x, y)is called withx=2andy=3, its output can be automatically saved tox=2_y=3_output.pkl. - Nested directories are also possible: e.g. the same output could be saved to
x=2/y=3/output.pkl.
- For example, when
- Customizable: Keyword arguments can be passed to control the serialization/deserialization processes.
- For example, if the function returns multiple numpy arrays (handled by
numpy.savezinternally), you could passcompress=Trueto enable compression.
- For example, if the function returns multiple numpy arrays (handled by
- Extensible: You can define custom
saveandloadfunctions to use your own file formats. - Lazy: When supported by the file format, cached results are lazy-loaded by default to speed up the function call and save memory.
- For example,
xarray.Datasetoutputs are loaded from.ncnetCDF-4 files usingxarray.open_dataset(lazy) instead ofxarray.load_dataarray(which eagerly loads the file contents into memory).
- For example,
The initial inspiration for this decorator came from a similar implementation called result_caching used internally by the Brain-Score project. While this was handy, it was also rather inflexible, so I forked it and added features to support my use cases.