The Pythonwiki introduces the following memoize decorators:
# note that this decorator ignores **kwargs
def memoize(obj):
cache = obj.cache = {}
@functools.wraps(obj)
def memoizer(*args, **kwargs):
if args not in cache:
cache[args] = obj(*args, **kwargs)
return cache[args]
return memoizer
However, as stated in the comment, it seems that it does not support kwargs. Let's deal with it.
# do not use "self" for a name of argument.
import inspect
def memoize(obj):
cache = obj.cache = {}
@functools.wraps(obj)
def memoizer(*args, **kwargs):
argdict = inspect.getcallargs(obj, *args, **kwargs)
argdict.pop('self', None) # if obj is a bound method, arguments includes "self"
argset = frozenset(argdict.iteritems()) # for Python3, use dict.items() instead
if argset not in cache:
cache[argset] = obj(*args, **kwargs)
return cache[argset]
return memoizer
The point is to use the standard library inspect. inspect.getcallargs ()
>>> def f(a, b, c=10):
... pass
...
>>> inspect.getcallargs(f, 1, 2)
{'a': 1, 'c': 10, 'b': 2}
Like, it makes the argument name and argument into a dictionary. inspect is useful in many ways.
Recommended Posts