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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With