I have some computationally intensive functions in my python script that I would like to cache. I went looking for solutions on stack overflow and found lots of links:
- https://stackoverflow.com/questions/4431703/python-resettable-instance-method-memoization-decorator
- https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
- http://pythonhosted.org/cachetools/
- https://pythonhosted.org/Flask-Cache/ (I've used this one for flask applications, but this one is not a flask application).
In the end, I ended up pasting this into my program. It seems simple enough -- and works fine.
class memoized(object):
'''Decorator. Caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned
(not reevaluated).
'''
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
if not isinstance(args, collections.Hashable):
return self.func(*args)
if args in self.cache:
return self.cache[args]
else:
value = self.func(*args)
self.cache[args] = value
return value
def __repr__(self):
'''Return the function's docstring.'''
return self.func.__doc__
def __get__(self, obj, objtype):
'''Support instance methods.'''
return functools.partial(self.__call__, obj)
However, I am wondering if there is a cannonical best practice in Python. I guess I assumed that there would be a very commonly used package to handle this and am confused about why this does not exist. http://pythonhosted.org/cachetools/ is only on version .6 and the syntax is more complex than simply adding a @memoize decorator, like in other solutions.