access to generator state

Peter Otten __peter__ at web.de
Thu Dec 2 14:45:09 EST 2004


Neal D. Becker wrote:

> 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

You get read access with generator.gi_frame.f_locals and can mess (as
always) with mutable variables, but not rebind the local variables:

>>> def gen():
...     a = 2
...     b = [3]
...     yield a*b[0]
...     yield a*b[0]
...
>>> g = gen()
>>> g.gi_frame.f_locals
{}
>>> g.next()
6
>>> g.gi_frame.f_locals
{'a': 2, 'b': [3]}
>>> g.gi_frame.f_locals["a"] = 137 # has no effect
>>> g.gi_frame.f_locals["b"][0] = 42
>>> g.next()
84
>>> g.gi_frame.f_locals
{'a': 2, 'b': [42]}

Peter




More information about the Python-list mailing list