At the moment, I’m doing stuff like the following, which is getting tedious:
run_once = 0
while 1:
if run_once == 0:
myFunction()
run_once = 1:
I’m guessing there is some more accepted way of handling this stuff?
What I’m looking for is having a function execute once, on demand. For example, at the press of a certain button. It is an interactive app which has a lot of user controlled switches. Having a junk variable for every switch, just for keeping track of whether it has been run or not, seemed kind of inefficient.
I would use a decorator on the function to handle keeping track of how many times it runs.
Now
my_functionwill only run once. Other calls to it will returnNone. Just add anelseclause to theifif you want it to return something else. From your example, it doesn’t need to return anything ever.If you don’t control the creation of the function, or the function needs to be used normally in other contexts, you can just apply the decorator manually as well.
This will leave
my_functionavailable for other uses.Finally, if you need to only run it once twice, then you can just do