## Python Caching decorator

Assume your object has a method that calculates a value that doesn't change in the object's lifetime. For example, you have a tree of objects and a characteristic of a node that is calculated recursively (e. g., depth of a subtree), and you are not going to change the whole tree after it is created. In this case a reasonable solution to improve performance is to calculate the value once on the first call and then cache it in a way. Here is a useful Python decorator for this:

def caching(fn):
name = fn.__name__
print name
cache_name = "_cache_" + name
def newmethod(self, *args, **kwargs):
if hasattr(self, cache_name):
return getattr(self, cache_name)
else:
value = fn(self, *args, **kwargs)
setattr(self, cache_name, value)
return value
newmethod.__name__ = name
return newmethod

And here is an example of usage:

class A(object):
@caching
def myattr(self):
print "Calculating it now..."
return 42

a = A()
print a.myattr() # outputs "Calculating it now...\n42"
print a.myattr() # outputs "42"


Enjoy using it!