Welcome, guest | Sign In | My Account | Store | Cart
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")

History

  • revision 3 (18 years ago)
  • previous revisions are not available