Skip to main content

@fused.cache

cache(
func: Callable[..., Any] | None = None,
cache_max_age: str | int = DEFAULT_CACHE_MAX_AGE,
cache_folder_path: str = "tmp",
concurrent_lock_timeout: str | int = 120,
cache_reset: bool | None = None,
cache_storage: StorageStr | None = None,
cache_key_exclude: Iterable[str] = None,
cache_verbose: bool | None = None,
**kwargs: Any
) -> Callable[..., Any]

Decorator to cache the return value of a function.

This function serves as a decorator that can be applied to any function to cache its return values. The cache behavior can be customized through keyword arguments.

Parameters

  • func (Callable) – The function to be decorated. If None, this returns a partial decorator with the passed keyword arguments.
  • cache_max_age (str | int) – A string with a numbered component and units. Supported units are seconds (s), minutes (m), hours (h), and days (d) (e.g. "48h", "10s", etc.).
  • cache_folder_path (str) – Folder to append to the configured cache directory.
  • concurrent_lock_timeout (str | int) – Max amount of time in seconds for subsequent concurrent calls to wait for a previous concurrent call to finish execution and to write the cache file.
  • cache_reset (bool | None) – Ignore cache_max_age and overwrite cached result.
  • cache_storage (StorageStr | None) – Set where the cache data is stored. Supported values are "auto", "mount" and "local". Auto will automatically select the storage location defined in options (mount if it exists, otherwise local) and ensures that it exists and is writable. Mount gets shared across executions where local will only be shared within the same execution.
  • cache_key_exclude (Iterable[str]) – An iterable of parameter names to exclude from the cache key calculation. Useful for arguments that do not affect the result of the function and could cause unintended cache expiry (e.g. database connection objects).
  • cache_verbose (bool | None) – Print a message when a cached result is returned.

Returns

Callable – A decorator that, when applied to a function, caches its return values according to the specified keyword arguments.

Examples

Use the @cache decorator to cache the return value of a function in a custom path.

@cache(path="/tmp/custom_path/")
def expensive_function():
# Function implementation goes here
return result

If the output of a cached function changes, for example if remote data is modified, it can be reset by running the function with the cache_reset keyword argument. Afterward, the argument can be cleared.

@cache(path="/tmp/custom_path/", cache_reset=True)
def expensive_function():
# Function implementation goes here
return result