Function to execute only once

Paul Rubin http
Fri Oct 14 15:25:07 EDT 2005


"PyPK" <superprad at gmail.com> writes:
> 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.

There's nothing built into Python for that.  You have to program the
function to remember whether it's already been called.  It sounds like
you're trying to avoid performing some side effect more than once.

Anyway, there's multiple ways you can do it.  The conceptually
simplest is probably just use an attribute on the function:

   tmp = 0       # you want to modify this as a side effect
   def execute():
     global tmp
     if not execute.already_called:
        tmp += 1
        execute.already_called = True
     return tmp
   execute.already_called = False

Other ways include using a class instance, using an iterator, etc.

Generally too, you might find it cleaner to avoid having side effects
like that.  Instead, put tmp itself inside a class instance:

    class Memo:
      def __init__(self):
        self.value = 0    # any side effects operate on this
        self.already_called = False

      def __call__(self):
        if not self.already_called:
           self.already_called = True
           self.value += 1
        return self.value

    execute = Memo()

Now you don't have global state cluttering things up, you can make
multiple instances easily, etc.



More information about the Python-list mailing list