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], defaultNone) – The function to wrap. When cache_results is used without parentheses (@cache_results), func is passed directly.maxsize (
Optional[int], default128) – Maximum number of entries to keep. When the limit is reached the oldest entry (FIFO) is evicted.Nonemeans unlimited.copy_on_return (
bool, defaultTrue) – IfTrue, acopy.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 toFalsewhen the result is known to be immutable or when performance is critical.per_instance (
bool, defaultFalse) –When
True, return a_PerInstanceCacheDescriptorinstead 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 beFalsewhen decorating plain functions.Note
Instance methods whose first parameter is
selfare auto-detected and routed to the per-instance descriptor even when this flag isFalse.
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): ...