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 details)
Built Distribution
File details
Details for the file contextcache-0.3.0.tar.gz
.
File metadata
- Download URL: contextcache-0.3.0.tar.gz
- Upload date:
- Size: 2.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.6.1 CPython/3.10.6 Darwin/22.6.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | ee04bf8ec0683c5a8d52df8097442328499d7c77c534c6f73167fe5acd63273a |
|
MD5 | 63509983ac7a015d87e617ef6c1a7617 |
|
BLAKE2b-256 | 55334cfd58fc6df62e1b7640de2b5215c9505696e9266eae833a8170c5452fb0 |
File details
Details for the file contextcache-0.3.0-py3-none-any.whl
.
File metadata
- Download URL: contextcache-0.3.0-py3-none-any.whl
- Upload date:
- Size: 2.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.6.1 CPython/3.10.6 Darwin/22.6.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | d0d91474eeee45606c84ea6a292b49277e63da807bb6360afd7e525d8cc4e363 |
|
MD5 | b879e4470b88202e348af3df56cf0f71 |
|
BLAKE2b-256 | 6b8b89416d3191a186825e394d0ae90e928968848df203f3383bfaf9fa845415 |