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
>>> from charmonium.cache import cache_decor, MemoryStore >>> @cache_decor(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.0.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 6ffa871f12e08c7d5e2e43423e3a0d87cc4a2383302bfb1cfacb48611c792253 |
|
MD5 | e673b6577a6a946ab392b3be30665eaf |
|
BLAKE2b-256 | 8e18ab828218062f0c73e0202d70d1c862d23e1cb7849a3197ec1d923642cdb4 |