spey.system.cache.cache_results

Contents

spey.system.cache.cache_results#

spey.system.cache.cache_results(func: Callable = None, *, maxsize: int = 128, copy_on_return: bool = True, per_instance: bool = False) Callable[source]#

Decorator that caches function results for identical arguments.

Parameters:
  • func (Optional[Callable], default None) – The function to wrap. When cache_results is used without parentheses (@cache_results), func is passed directly.

  • maxsize (Optional[int], default 128) – Maximum number of entries to keep. When the limit is reached the oldest entry (FIFO) is evicted. None means unlimited.

  • copy_on_return (bool, default True) – If True, a copy.deepcopy() of the cached result is returned on every call. This prevents callers from mutating the cached object at the cost of a copy. Set to False when the result is known to be immutable or when performance is critical.

  • per_instance (bool, default False) –

    When True, return a _PerInstanceCacheDescriptor instead of a plain wrapper. The descriptor installs a dedicated cache on each instance the first time the method is accessed, so two distinct instances (even of the same class) never share cache entries. Use this when decorating instance methods that must remain isolated across objects. Must be False when decorating plain functions.

    Note

    Instance methods whose first parameter is self are auto-detected and routed to the per-instance descriptor even when this flag is False.

Examples

Without arguments (uses defaults):

@cache_results
def expensive(x, arr):
    ...

With arguments:

@cache_results(maxsize=64, copy_on_return=False)
def expensive(x, arr):
    ...

Per-instance caching for a method (typically applied via __init_subclass__ rather than directly):

@cache_results(per_instance=True)
def config(self, allow_negative_signal=True, poi_upper_bound=10.0):
    ...