Memoize
Will cache function return values based on the arguments.
def memoize(
function: Union[None, Callable[P, R]] = None,
key: Union[None, Callable[P, R]] = None,
storage: Optional[Storage] = None,
allow_nonlocals: bool = False,
) -> Union[Callable[[Callable[P, R]], MemoizedFunction[P, R]], MemoizedFunction[P, R]]:
...
Example:
@solara.memoize
def mean(values):
return sum(values) / len(values)
If a key function is provided, it will be used to generate the cache key based on the arguments instead. This is useful in situations where the arguments are not hashable, but a unique key can be generated based on the arguments.
Also used in situations where the arguments are expensive to hash, but a cheaper key that is unique exists. For example using the filename instead of the file content.
Example:
@solara.memoize(key=lambda df, column: (id(df), column))
def mean(df, column):
return df[column].mean()
Without the key function, the above would fail because a DataFrame is not hashable.
The function name and function code are added to the argument based key, together making up a unique cache key.
Nonlocals variables are not included in the key, and are not allowed by default. Pass allow_nonlocals=True
to allow nonlocals variables, or add them as arguments to the function.
Globals are by default allowed, and also not included in the key. Solara will try to detect if globals are
changed, and if so, will raise a ValueError.
If a storage is provided, it will be used to store the cached values. If no storage is provided, the shared storage will be used. This is useful in situations where the cache should be shared between different functions to avoid excessive memory usage by limiting the number of cache entries or the memory content.
The storage can be any object that implements the MutableMapping interface, for instance a dict or
a cachetools.LRUCache. Or a new instance of solara.cache.Memory
, see caching
for cache storage options.
The return value of the decorator behaves like the original function, but also has a few attributes:
storage
: the storage used to cache the valueskey
: the key function used to generate the keyfunction
: the original functionuse_thread
: a hook that will execute the function in a thread, and return a Result object If the value is already cached, the function will not be executed in a thread.
See also the reference on caching for more caching details.
We cache 2 values. Each computation takes 3 seconds. If you go back to a cached value, you will see the result immediately.
Running...