https://github.com/peter554/contextcache
Cache a python function, only in certain contexts
https://github.com/peter554/contextcache
Last synced: about 2 months ago
JSON representation
Cache a python function, only in certain contexts
- Host: GitHub
- URL: https://github.com/peter554/contextcache
- Owner: Peter554
- Created: 2023-10-17T20:26:10.000Z (almost 3 years ago)
- Default Branch: master
- Last Pushed: 2023-10-19T21:32:40.000Z (almost 3 years ago)
- Last Synced: 2026-05-05T13:34:30.615Z (3 months ago)
- Language: Python
- Homepage:
- Size: 33.2 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# contextcache
[](https://github.com/Peter554/contextcache/actions/workflows/ci.yml)
Cache a python function *only in certain contexts*.
## Usage
Here's an example:
```sh
cat example.py
```
```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("Without caching")
print(double(1))
print(double(1))
# With caching.
with contextcache.use_caching(double):
print("\nWith caching")
print(double(1))
print(double(1))
# Without caching, again.
print("\nWithout caching, again")
print(double(1))
print(double(1))
```
Here's the output:
```sh
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.