Skip to main content

No project description provided

Project description

contextcache

CI

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


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)

Uploaded Source

Built Distribution

contextcache-0.3.0-py3-none-any.whl (2.8 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page