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)
      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):
  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!

Add a comment

Python Metaclasses

(There is an awesome post explaining the same thing at StackOverflow; I'll try to make in shorter and more interesting.)

Why is C++ crappy as hell while Python is shining like a crown of the British Empire? Both are designed to be object-oriented languages, but the Python is the only true one. Everything in Python are objects. Literally, everything. Integers are objects, modules are objects and even object types are objects too.

Objects have constuctors. So object types have constructors too.

The built-in object-type constructor is named type and works like

mytype = type("MyTypeName", (parent1,), {'method1': lambda self: return None})

So, it takes name of the new type, tuple of parent types and dictionary of methods. That's enough to construct any class.

Yeah, it is THAT simple in Python.

type is also a class, and any standard type in Python is an instance of this class. So why not to subclass it?

Add a comment

Read more: Python Metaclasses