2008.09.19 15:48
python decorator to make function or method cachable
For one project I just needed to make a decorator which turns any Python function or method into cachable version. I mean, if the function is called several times with the same arguments, the result is being take from cache. Finally I managed to do it. Here it is:
class cachable_function(object):
do = None
cache = None
def __init__(self, do):
self.do = do
self.cache = {}
def arguments2index(self, arguments, named_arguments):
index = ()
for key in named_arguments:
index += (key, named_arguments[key]),
index = (arguments, index)
return index
def __call__(self, *arguments, **named_arguments):
index = self.arguments2index(arguments, named_arguments)
try:
result = self.cache[index]
except KeyError:
result = self.do(*arguments, **named_arguments)
self.cache[index] = result
return result
class cachable_method(cachable_function):
def __get__(cachable_method_self, method_s_object_self, type=None):
def cachable_method(*arguments, **named_arguments):
result = cachable_method_self.__call__(method_s_object_self, *arguments, **named_arguments)
return result
return cachable_method
if __name__ == \'__main__\':
class klasa:
@cachable_method
def f1(self, a, b):
return a/b
k = klasa()
print k.f1(10, 2)
print k.f1(10, 5)
print k.f1(10, 2)
print k.f1(10, 5)
print k.f1(b=2, a=10)
print k.f1(b=2, a=10)
I haven\'t tested it well yet, but it seems to work.
komentarze:
powrót na stronę główną
RSS