Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way of having a function only execute once in a loop

Tags:

python

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.

like image 260
Marcus Ottosson Avatar asked Nov 05 '10 05:11

Marcus Ottosson


People also ask

Which Javascript function is used to execute a task only once?

If you're using Ramda, you can use the function "once". Accepts a function fn and returns a function that guards invocation of fn such that fn can only ever be called once, no matter how many times the returned function is invoked.


1 Answers

I would use a decorator on the function to handle keeping track of how many times it runs.

def run_once(f):     def wrapper(*args, **kwargs):         if not wrapper.has_run:             wrapper.has_run = True             return f(*args, **kwargs)     wrapper.has_run = False     return wrapper   @run_once def my_function(foo, bar):     return foo+bar 

Now my_function will only run once. Other calls to it will return None. Just add an else clause to the if if 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.

action = run_once(my_function) while 1:     if predicate:         action() 

This will leave my_function available for other uses.

Finally, if you need to only run it once twice, then you can just do

action = run_once(my_function) action() # run once the first time  action.has_run = False action() # run once the second time 
like image 88
aaronasterling Avatar answered Sep 24 '22 14:09

aaronasterling