pydvl.utils.caching.memory
¶
InMemoryCacheBackend
¶
Bases: CacheBackend
In-memory cache backend that stores results in a dictionary.
Implements the CacheBackend interface for an in-memory-based cache. Stores cache entries as values in a dictionary, keyed by cache key. This allows sharing evaluations across threads in a single process.
The implementation is not thread-safe.
ATTRIBUTE | DESCRIPTION |
---|---|
cached_values |
Dictionary used to store cached values. |
Example
Basic usage:
>>> from pydvl.utils.caching.memory import InMemoryCacheBackend
>>> cache_backend = InMemoryCacheBackend()
>>> cache_backend.clear()
>>> value = 42
>>> cache_backend.set("key", value)
>>> cache_backend.get("key")
42
Callable wrapping:
>>> from pydvl.utils.caching.memory import InMemoryCacheBackend
>>> cache_backend = InMemoryCacheBackend()
>>> cache_backend.clear()
>>> value = 42
>>> def foo(x: int):
... return x + 1
...
>>> wrapped_foo = cache_backend.wrap(foo)
>>> wrapped_foo(value)
43
>>> wrapped_foo.stats.misses
1
>>> wrapped_foo.stats.hits
0
>>> wrapped_foo(value)
43
>>> wrapped_foo.stats.misses
1
>>> wrapped_foo.stats.hits
1
Source code in src/pydvl/utils/caching/memory.py
wrap
¶
wrap(
func: Callable, *, config: Optional[CachedFuncConfig] = None
) -> CachedFunc
Wraps a function to cache its results.
PARAMETER | DESCRIPTION |
---|---|
func |
The function to wrap.
TYPE:
|
config |
Optional caching options for the wrapped function.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
CachedFunc
|
The wrapped cached function. |