Function to execute only once

snoe case.nelson at gmail.com
Fri Oct 14 16:34:19 EDT 2005


I've been seeing alot about decorators and closures lately and my
initial thought was that this would be a good place to use them instead
of wrapping it around a class. That was my initial thought :) What I
came up with was this:
def execute_once(fn):
     result = None
     def executor(*args, **kwargs):
         if not result:
            result = fn(*args, **kwargs)
         return result
     return executor

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

def func1(tmp):
    execute(tmp)

def func2(tmp):
    execute(tmp)

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

It gives the following error:
init tmp: 0
Traceback (most recent call last):
  File "C:\Download\test.py", line 26, in ?
    func1(tmp)
  File "C:\Download\test.py", line 19, in func1
    execute(tmp)
  File "C:\Download\test.py", line 5, in executor
    if not result:
UnboundLocalError: local variable 'result' referenced before assignment

Makes sense to me, except I expected some closure 'magic'. I thought
that when I wrapped executor() inside execute_once() the name result
would be available to executor(). What am I missing here (I expect the
answer to be 'alot') but is this type of solution valid for this
problem?




More information about the Python-list mailing list