access to generator state

Sean Ross seandavidross at hotmail.com
Thu Dec 2 20:38:13 CET 2004


"Neal D. Becker" <ndbecker2 at verizon.net> wrote in message
news:mailman.7029.1102012604.5135.python-list at python.org...
> 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





More information about the Python-list mailing list