"Neal D. Becker" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > I am converting optimization code from legacy C to python. Generators are a > HUGE convenience, because the original code structures have the optimizer > as the main code calling your function, while I want to invert these roles. > I want to call the optimizer to perform just one step at a time. > > So, the optimizer must preserve it's state. The classic way to do this is > with classes. Problem is, I need to figure out just what variables need to > be preserved across calls. > > Using yield, this is trivial to achieve. All state is automatically saved. > > Only one problem. Is there any way to access the state of a generator > externally? In other words, the generator saves all it's local variables. > Can an unrelated object then query the values of those variables? (In this > case, to get at intermediate results) >
>>> def twice(): ... for i in range(0,2): ... yield i ... >>> gen = twice() >>> gen.gi_frame.f_locals {} >>> gen.next() 0 >>> gen.gi_frame.f_locals {'i': 0} >>> gen.next() 1 >>> gen.gi_frame.f_locals {'i': 1} >>> gen.next() Traceback (most recent call last): File "<interactive input>", line 1, in ? StopIteration >>> HTH, Sean -- http://mail.python.org/mailman/listinfo/python-list