access to generator state
Kent Johnson
kent3737 at yahoo.com
Thu Dec 2 14:17:47 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 this
> case, to get at intermediate results)
>
You could make the generator a method of a class and store the generator state in instance variables
instead of local variables:
>>> class Gen:
... def __init__(self):
... self.i = 0
... def __call__(self):
... while True:
... yield self.i
... self.i += 1
...
>>> g=Gen()
>>> g.i
0
>>> iter=g()
>>> iter.next()
0
>>> g.i
0
>>> iter.next()
1
>>> g.i
1
HTH
Kent
More information about the Python-list
mailing list