Update variable in python after each loop
Question: Been struggling with this for a little while, I want the variable "result" to
be updated after each loop of the function so that next time it steps through
the function it will return something new. I have tried assigning result
outside of my function then attempting to update it like that but haven't had
any look.

    
    
    def move2(msg):
        global result
        if result is None:
            print "Error result variable does not have a value"
        elif result is "rtn":
            rtn()
            result = "fwd"
            return result
        elif result is "fwd":
            fwd()
            result = "step"
            return result
        elif result is "step":
            step()
            result = "rtn"
            return result
        else:
            print "ERROR"
    

To note I am fairly new to python and am not opposed to other approaches if
any of you have suggestions. Thanks


Answer: You are trying to make your function stateful which is generally a bad idea.
Make it a class instead, like

    
    
    from itertools import cycle
    
    class StatefulCaller:
        def __init__(self, state_fns, repeat=True):
            if repeat:
                state_fns = cycle(state_fns)
            self.fn_iter = iter(state_fns)
        def __call__(self):
            return next(self.fn_iter)()
    

which you can then use like:

    
    
    rtn  = lambda: "rtn"
    fwd  = lambda: "fwd"
    step = lambda: "step"
    
    myfn = StatefulCaller([rtn, fwd, step])
    
    for i in range(10):
        print(i, myfn())
    

which results in

    
    
    0 rtn
    1 fwd
    2 step
    3 rtn
    4 fwd
    5 step
    6 rtn
    7 fwd
    8 step
    9 rtn
    

