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?

4
  • Possible duplicate of Efficient way of having a function only execute once in a loop Commented Nov 23, 2015 at 22:40
  • 1
    Did you try to use a global variable only inside the function ? Is it compliant with your requirements ? Commented Nov 23, 2015 at 22:40
  • @LaurentH. thought about that, but I'm trying to avoid any outside reference :S Commented Nov 23, 2015 at 22:44
  • 1
    What kinda of loop? Does it by chance have an index you can pass in? Commented Nov 24, 2015 at 0:39

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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 

Comments

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 Comment

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.
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'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.