Function to execute only once

Bengt Richter bokr at oz.net
Sun Oct 16 12:45:43 EDT 2005


On 14 Oct 2005 12:11:58 -0700, "PyPK" <superprad at gmail.com> wrote:

>Hi if I have a function called
>tmp=0
>def execute():
>    tmp = tmp+1
>    return tmp
>
>also I have
>def func1():
>    execute()
>    ....
>and
>def func2():
>    execute()
>    ....
>
>now I want execute() function to get executed only once. That is the
>first time it is accessed.
>so taht when funcc2 access the execute fn it should have same values as
>when it is called from func1.
>

You could have the execute function replace itself with a function
that returns the first result from there on, e.g., (assuming you want
the global tmp incremented once (which has bad code smell, but can be expedient ;-)):

 >>> tmp = 0
 >>> def execute():
 ...     global tmp, execute
 ...     tmp = cellvar = tmp + 1
 ...     def execute():
 ...         return cellvar
 ...     return tmp
 ...
 >>> def func1():
 ...     return execute() # so we can see it
 ...
 >>> def func2():
 ...     return execute() # so we can see it
 ...
 >>> func1()
 1
 >>> tmp
 1
 >>> func2()
 1
 >>> tmp
 1
 >>> execute()
 1
 >>> execute
 <function execute at 0x02EF702C>
 >>> import dis
 >>> dis.dis(execute)
   5           0 LOAD_DEREF               0 (cellvar)
               3 RETURN_VALUE

But if you want to call the _same_ "execute" callable that remembers that
it's been called and does what you want, you need a callable that can
remember state one way or another. A callable could be a function with
a mutable closure variable or possibly a function attribute as shown in
other posts in the thread, or maybe a class bound method or class method,
or even an abused metaclass or decorator, but I don't really understand
what you're trying to do, so no approach is likely to hit the mark very well
unless you show more of your cards ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list