No project description provided
Project description
contextcache
Cache a python function only in certain contexts.
Usage
Here's an example:
cat example.py
import contextcache
# Define a private CacheContextVar to store the cached values. Don't touch this CacheContextVar from anywhere else!
# You need to define a separate CacheContextVar for every function for which you want to enable caching.
# Use `None` as the default.
_double_cache = contextcache.CacheContextVar("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.3.0.tar.gz
(2.3 kB
view hashes)
Built Distribution
Close
Hashes for contextcache-0.3.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | d0d91474eeee45606c84ea6a292b49277e63da807bb6360afd7e525d8cc4e363 |
|
MD5 | b879e4470b88202e348af3df56cf0f71 |
|
BLAKE2b-256 | 6b8b89416d3191a186825e394d0ae90e928968848df203f3383bfaf9fa845415 |