No project description provided
Project description
contextcache
Cache a python function only in certain contexts.
Usage
Here's an example:
# example.py
import contextvars
import contextcache
# Define a private ContextVar to store the cached values. Don't touch this ContextVar!
# You need to define a separate ContextVar for every function for which you want to enable caching.
# contextcache can't do this for you since ContextVars must be global. Use `None` as the default.
_double_cache = contextvars.ContextVar("double_cache", default=None)
# Use the `enable_caching` decorator to enable context caching for `double`.
@contextcache.enable_caching(_double_cache)
def double(n: int) -> int:
print(f"Doubling {n}, working...")
return n * 2
# Without caching.
print(f"Without caching")
print(double(1))
print(double(1))
# With caching.
with contextcache.use_caching(double):
print(f"\nWith caching")
print(double(1))
print(double(1))
# Without caching, again.
print(f"\nWithout caching, again")
print(double(1))
print(double(1))
Here's the output:
python example.py
Without caching
Doubling 1, working...
2
Doubling 1, working...
2
With caching
Doubling 1, working...
2
2
Without caching, again
Doubling 1, working...
2
Doubling 1, working...
2
See the tests for further examples.
Caveats
- Function arguments must be hashable.
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
contextcache-0.2.0.tar.gz
(2.0 kB
view hashes)
Built Distribution
Close
Hashes for contextcache-0.2.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | eff80944cf750e03b0dde88934f0684596c8564a143997aa633157d3082c4829 |
|
MD5 | 9a5a2c72a2b570d320092d871ee9a2e7 |
|
BLAKE2b-256 | 9fd69414b72e04264f4cb44af42c87cc3759dbb2b638724c979bbe6d144e70d9 |