Skip to content

Commit

Permalink
[IMP] util/misc: cache unique functions
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
diagnoza committed Feb 22, 2024
1 parent aa7131e commit f8cf72c
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src/util/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit f8cf72c

Please sign in to comment.