Update llnl.util.lang.memoized so that Sphinx can extract signature (#11055)

Replace the original implementation of the "memoized" decorator with
an implementation that exposes the docstring and arguments of the
wrapped function. This is achieved using functools.wraps.
This commit is contained in:
Massimiliano Culpo 2019-03-30 01:11:44 +01:00 committed by Peter Scheibel
parent def5b23763
commit e3f00750e8

View File

@ -168,30 +168,24 @@ def union_dicts(*dicts):
return result return result
class memoized(object): def memoized(func):
"""Decorator that caches the results of a function, storing them """Decorator that caches the results of a function, storing them in
in an attribute of that function.""" an attribute of that function.
"""
func.cache = {}
def __init__(self, func): @functools.wraps(func)
self.func = func def _memoized_function(*args):
self.cache = {}
def __call__(self, *args):
if not isinstance(args, collections.Hashable): if not isinstance(args, collections.Hashable):
# Not hashable, so just call the function. # Not hashable, so just call the function.
return self.func(*args) return func(*args)
if args not in self.cache: if args not in func.cache:
self.cache[args] = self.func(*args) func.cache[args] = func(*args)
return self.cache[args]
def __get__(self, obj, objtype): return func.cache[args]
"""Support instance methods."""
return functools.partial(self.__call__, obj)
def clear(self): return _memoized_function
"""Expunge cache so that self.func will be called again."""
self.cache.clear()
def list_modules(directory, **kwargs): def list_modules(directory, **kwargs):