Function to execute only once

snoe case.nelson at
Fri Oct 14 22:34:19 CEST 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

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

def func1(tmp):

def func2(tmp):

print 'init tmp:', tmp
print 'ran func1 tmp:', tmp
print 'ran func2 tmp:', tmp

It gives the following error:
init tmp: 0
Traceback (most recent call last):
  File "C:\Download\", line 26, in ?
  File "C:\Download\", line 19, in func1
  File "C:\Download\", 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

More information about the Python-list mailing list