From f8cf72c5e4490eadaa5c41698c9ecb5eb9176c88 Mon Sep 17 00:00:00 2001 From: diagnoza Date: Thu, 22 Feb 2024 20:54:29 +0000 Subject: [PATCH] [IMP] util/misc: cache unique functions Improves caching to not simply cache the result of the first call of a function, but each *unique* (based on args and kwargs, taking into consideration their order) call. --- src/util/misc.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/util/misc.py b/src/util/misc.py index 20f52a1b..b886c344 100644 --- a/src/util/misc.py +++ b/src/util/misc.py @@ -30,14 +30,15 @@ def _cached(func): - sentinel = object() + func._cache = {} @functools.wraps(func) def wrapper(*args, **kwargs): - result = getattr(func, "_result", sentinel) - if result == sentinel: - result = func._result = func(*args, **kwargs) - return result + key = (args, tuple(sorted(kwargs.items()))) + + if key not in func._cache: + func._cache[key] = func(*args, **kwargs) + return func._cache[key] return wrapper