Provides a decorator for caching a function and an equivalent command-line util.
Project description
Provides a decorator for caching a function and an equivalent command-line util.
It wraps an ordinary function. Whenever the function is called with the same arguments, the result is loaded from the cache instead of computed.
Quickstart
$ pip install charmonium.cache
>>> import charmonium.cache as ch_cache >>> @ch_cache.decor(ch_cache.MemoryStore.create()) ... def square(x): ... print('computing') ... return x**2 ... >>> square(4) computing 16 >>> square(4) # square is not called again; answer is just looked up 16
Customization
cache_decor is flexible because it supports multiple backends.
MemoryStore: backed in RAM for the duration of the program
FileStore: backed in an index file which is loaded on first call.
DirectoryStore: backed in a directory. Results are stored as individual files in that directory, and they are loaded lazily. Use this for functions that return large objects.
Custom stores: to create a custom store, just extend ObjectStore and implement a dict-like interface.
FileStore and DirectoryStore can both themselves be customized by:
Providing a cache_path (conforming to the PathLike interface), e.g. an S3Path object.
Providing a serializer (conforming to the Serializer interface), e.g. [pickle] (default), [cloudpickle], [dill], [messagepack].
cache_decor also takes a “state function” which computes the value of some external state that this computation should depend on. Unlike the arguments (which the cache explicitly depends on), values computed with a different state are evicted out, so this is appropriate when you never expect to revisit a prior state (e.g. modtime of a file could be a state, as in make_file_state_fn).
CLI
# cache a commandline function based on its args read n cache -- compute_prime ${n} # cache based on args AND file-modtime # recompiles when main.c is newer than the most recent compile cache --file main.c -- gcc main.c -o main
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for charmonium.cache-0.3.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 54c786a1cacf65c47133f9c81f78c63702022e912cad8e2955954485b37a18f9 |
|
MD5 | cb89586e26d4aca8c5961a07affcc41c |
|
BLAKE2b-256 | af54d198d5f7f8aa8d640665c51b8fe9ccc122246db3cfcef7e3ca2fd69c56ca |