Question

So I'm trying to learn the leap-motion SDK and re-learning python after not touching it in 4-5 years and I'm running into a problem with generators in python 2.7

Basically I have a list of words and I want to print the next word in the list every time the leap motion picks up a new 'Circle' gesture. What I'm seeing happening is that every time the on_frame callback fires only the first word in the list is printed. I believe what is happening is that the python run-time is forgetting the state of the generator between events. Is there some way persist the generators state between gesture events?

if not frame.hands.is_empty:
        for gesture in frame.gestures():
            if gesture.type == Leap.Gesture.TYPE_CIRCLE:
                circle = CircleGesture(gesture)
                # Determine clock direction using the angle between the pointable and the circle normal
                action = None
                if circle.pointable.direction.angle_to(circle.normal) <= Leap.PI/4:
                    action = GestureActions.clockwiseCircleGesture()
                else:
                    action = GestureActions.counterClockwiseCircleGesture()

                print action.next()

  def clockwiseCircleGesture():
       words = ["You", "spin", "me", "right", "round", "baby", "right", "round", "like", "a", "record", "baby",                          "Right", "round", "round", "round", "You", "spin", "me", "right", "round", "baby", "Right", "round", "like", "a",
         "record", "baby", "Right", "round", "round", "round"]
      for word in words:
          yield word

Any insight into this would be great. Thanks

Était-ce utile?

La solution

I suspect your action variable is being reset each time the event is fired.

Initialize the generators outside of the event handling function. It looks like you might want two, clockwise_action and counterclockwise_action.

Autres conseils

Not familiar with python but this is a common problem when people are learning generators/iterators/enumerators/whatever. You're recreating the iterator every time through the loop and losing state.

Instead create each one at most once

clockwise = GestureActions.clockwiseCircleGesture()
counter_clockwise = GestureActions.counterClockwiseCircleGesture()
# then

action = clockwise if foo else counter_clockwise

action.next()
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top