File tree Expand file tree Collapse file tree
core/libs/commonwealth/src/commonwealth/utils Expand file tree Collapse file tree Original file line number Diff line number Diff line change 99def temporary_cache (timeout_seconds : float = 10 ) -> Callable [[F ], F ]:
1010 """Decorator that creates a cache for specific inputs with a configured timeout in seconds.
1111
12+ The wrapped function exposes an `invalidate()` attribute that drops every cached entry,
13+ forcing the next call to re-execute the function. Useful when the cached data is known
14+ to be stale (e.g. after a write that mutates the underlying state).
15+
1216 Args:
1317 timeout_seconds (float, optional): Timeout to be used for cache invalidation. Defaults to 10.
1418
@@ -35,6 +39,11 @@ def wrapper(*args: Any) -> Any:
3539 cache [args ] = function_return
3640 return function_return
3741
42+ def invalidate () -> None :
43+ cache .clear ()
44+ last_sample_time .clear ()
45+
46+ wrapper .invalidate = invalidate # type: ignore[attr-defined]
3847 return wrapper # type: ignore
3948
4049 return inner_function
Original file line number Diff line number Diff line change @@ -24,3 +24,16 @@ def test_nested_settings_save_load() -> None:
2424
2525 # Check if all cache values are invalid after waiting for a long time
2626 assert all (original_output [key ] != cached_function (key ) for key in inputs )
27+
28+
29+ def test_temporary_cache_invalidate () -> None :
30+ inputs = ["first" , "second" , "third" ]
31+ original_output = {key : cached_function (key ) for key in inputs }
32+
33+ # Cache is still warm: same call returns the same value
34+ assert all (original_output [key ] == cached_function (key ) for key in inputs )
35+
36+ # Force invalidation; subsequent calls must re-execute the function
37+ cached_function .invalidate () # type: ignore[attr-defined]
38+
39+ assert all (original_output [key ] != cached_function (key ) for key in inputs )
You can’t perform that action at this time.
0 commit comments