Search code examples
pythonwhile-loopreal-time

Returning values from inside a while loop in python


I don't know if this is a simple question or impossible or anything, but I couldn't find anything on it so I figured I would ask it.

Is it possible to return values from a while loop while that loop is still running? Basically what I want to do is have a vector constantly updating within a while loop, but able to return values when asked without stopping the while loop. Is this possible? Do I just have to break up the program and put the while loop in a separate thread, or can I do it within one function?

Also I would prefer a method that is not computationally intensive (obviously), and one compatible with a rate-limited while loop as this one will certainly be rate-limited.

Again, if this is a stupid question just tell me and I will delete it, but I wasn't able to find documentation on this.

Code I am trying to implement this with:

def update(self, x_motion, y_motion, z_motion):
        self.x_pos += self.x_veloc
        self.y_pos += self.y_veloc
        self.z_pos += self.z_veloc
        self.x_veloc += self.x_accel
        self.y_veloc += self.y_accel
        self.z_veloc += self.z_accel
        self.x_accel = x_motion[2]
        self.y_accel = y_motion[2]
        self.z_accel = z_motion[2]
while True:
self.update(x_motion, y_motion, z_motion)

print vector.x_accel

Something along those lines at least. It is important that these return outside of the while loop, so that the while loop runs in the background, but it only gives results when asked, or something like that.


Solution

  • Create a generator instead.

    def triangle():
      res = 0
      inc = 1
      while True:
        res += inc
        inc += 1
        yield res
    
    t = triangle()
    print next(t)
    print next(t)
    print next(t)
    print next(t)
    

    EDIT:

    Or perhaps a coroutine.

    def summer():
      res = 0
      inc = 0
      while True:
        res += inc
        inc = (yield res)
    
    s = summer()
    print s.send(None)
    print s.send(3)
    print s.send(5)
    print s.send(2)
    print s.send(4)