py_research.caching module#

On-the-fly, file-based caching of function return values.

class FileCache(path, max_cache_time=datetime.timedelta(days=7))[source]#

Bases: object

Local, directory-based cache for storing function results.

Parameters:
path: Path#

Root directory for storing cached results.

max_cache_time: timedelta = datetime.timedelta(days=7)#

After how long to invalidate cached objects and recompute.

function(func: Callable[[P], R]) Callable[[P], R][source]#
function(*, id_arg_subset: list[int] | list[str] | None = None, use_raw_arg: bool = False, id_callback: Callable[[P], dict[str, Any] | None] | None = None, use_json: bool = True) Callable[[Callable[[P], R]], Callable[[P], R]]

Decorator to cache wrapped function.

Parameters:
  • func – Function to cache.

  • id_arg_subset – Number or name of the arguments to base hash id of result on.

  • use_raw_arg – If True, use the unhashed, string-formatted value of the id arg as filename. Only works for single id arg.

  • id_callback – Callback function to use for retrieving a unique id from the arguments.

  • use_json – Whether to use JSON as the format for caching dicts (instead of YAML).

get_cache(name=None, root_path=None, max_cache_time=datetime.timedelta(days=7))[source]#

Return a named cache instance private to the calling module.

Parameters:
  • name (str | None) – Name of the cache (directory) to create.

  • root_path (Path | None) – Root directory, where to store cache.

  • max_cache_time (timedelta) – After how many days to invalidate cached objects and recompute.

Returns:

A cache instance.