Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Run code segment only once inside infinite loop function..?

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?

like image 258
Sam Avatar asked May 12 '26 18:05

Sam


2 Answers

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.

like image 147
R Nar Avatar answered May 15 '26 09:05

R Nar


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 
like image 38
MaxNoe Avatar answered May 15 '26 09:05

MaxNoe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!