Function to execute only once

snoe case.nelson at gmail.com
Fri Oct 14 17:08:59 EDT 2005


The problem seemed to be because I was rebinding result inside
executor. Can someone explain why it works below but not in the first
one?

Also why is it if I set tmp as a global and don't pass it as a
paremeter to the various functions as per the OP that I get an
"UnboundLocalError: local variable 'tmp' referenced before assignment"?

def execute_once(fn):
    print "in execute_once"
    result = {}
    def executor(*args, **kwargs):
        if fn not in result:
            result[fn] = fn(*args, **kwargs)
        return result[fn]
    return executor

@execute_once
def execute(tmp):
    print "in execute"
    tmp = tmp+1
    return tmp

def func1(tmp):
    return execute(tmp)

def func2(tmp):
    return execute(tmp)

tmp = 0
print 'init tmp:', tmp
tmp = func1(tmp)
print 'ran func1 tmp:', tmp
tmp = func2(tmp)
print 'ran func2 tmp:', tmp
tmp = func1(tmp)
print 'ran func1 tmp:', tmp

OUTPUT:
in execute_once
init tmp: 0
in execute
ran func1 tmp: 1
ran func2 tmp: 1
ran func1 tmp: 1




More information about the Python-list mailing list