def func_once(func): "A decorator that runs a function only once." def decorated(*args, **kwargs): try: return decorated._once_result except AttributeError: decorated._once_result = func(*args, **kwargs) return decorated._once_result return decorated def method_once(method): "A decorator that runs a method only once." attrname = "_%s_once_result" % id(method) def decorated(self, *args, **kwargs): try: return getattr(self, attrname) except AttributeError: setattr(self, attrname, method(self, *args, **kwargs)) return getattr(self, attrname) return decorated # Example, will only parse the document once @func_once def get_document(): import xml.dom.minidom return xml.dom.minidom.parse("document.xml")