3

I have a function that is being run over and over again. Inside that function I want a specific segment to be run only the first time the function is run.

I can't use any variables from outside the functions, e.g.

    firstTime = True

    myFunction(firstTime): #function is inside a loop
        if firstTime == True:
            #code I want to run only once
            firstTime = False
        #code I want to be run over and over again

Neither do I want to use a global variable.

Any ideas how to accomplish this?

Sam
  • 39
  • 1
  • 4
  • Possible duplicate of [Efficient way of having a function only execute once in a loop](http://stackoverflow.com/questions/4103773/efficient-way-of-having-a-function-only-execute-once-in-a-loop) – R Nar Nov 23 '15 at 22:40
  • 1
    Did you try to use a global variable only inside the function ? Is it compliant with your requirements ? – Laurent H. Nov 23 '15 at 22:40
  • @LaurentH. thought about that, but I'm trying to avoid any outside reference :S – Sam Nov 23 '15 at 22:44
  • 1
    What kinda of loop? Does it by chance have an index you can pass in? – Spaceman Nov 24 '15 at 00:39

4 Answers4

5

Make use of mutable default arguments:

>>> def Foo(firstTime = []):
    if firstTime == []:
        print('HEY!')
        firstTime.append('Not Empty')
    else:
        print('NICE TRY!')


>>> Foo()
HEY!
>>> Foo()
NICE TRY!
>>> Foo()
NICE TRY!

why does this work? Check this question out for more details.

Community
  • 1
  • 1
R Nar
  • 5,465
  • 1
  • 16
  • 32
1

You could use a class that implements the __call__ magic method. This would have the advantage that you could use multiple instances or reset the instance.

class MyFunction():
    def __init__(self):
        self.already_called = False

    def __call__(self):
        if not self.already_called:
            print('init part')
            self.already_called = True
        print('main part')

func = MyFunc()
func()
func()

This will result in:

init part
main part
main part 
MaxNoe
  • 14,470
  • 3
  • 41
  • 46
1

May I get 100 years in hell for this:

#Actually may I not get 100 years in hell for this; my method has the advantage that you can run every single part of it with no hitch whereas, all the other code requires you to run some other part 'only once'.
try:
    if abc=='123':
        print("already done")
except:
    #Your code goes here.
    abc='123'

That should run the code in the try statement just once . ... now of course you could check for variable existence with if 'myVar' in locals(): but I like it better this way.

  • 1
    Imagine someone reading that code and trying to understand what it's supposed to do... So, yes, 100 years in hell is probably a good response for this. – moschlar Nov 07 '18 at 08:24
0

This is a refinement of my previous code. Something tells me I can do something with var()['VerySpecificVariableName'] though. IDK, this one won't hide exceptions though

try:
    if VerySpecificVariableName=='123':
        print("You did it already.")
except NameError as e:
    if not ('VerySpecificVariableName' in repr(e)):
        raise
    print ('your code here')
    VerySpecificVariableName='123'