Can I copy a generators state and then backtrack to it if necessary?

Tim Peters tim.one at home.com
Sat Jul 21 23:41:06 EDT 2001


[Stephen Horne]
> I don't seem to be getting much response. Please help!!!

There are only two people who can answer this stuff, and I already did, so
you'll have to try harder to make me feel guilty <wink>.

> To restate the problem, I want to know how to modify the following
> code...
>
>   from __future__ import generators
>
>   def test () :
>     for a in xrange (4) :
>       yield a
>
>   a = test ()
>
>   print a.next ()
>   print a.next ()
>
>   b = a
>
>   print a.next ()
>   print a.next ()
>
>   print b.next ()
>   print b.next ()
>
> So that the 'b=a' line takes a copy of a - rather than just making a
> reference.

You cannot -- it's not supported directly.  Even if you used Stackless
Python and used full-blown continuations, you still couldn't.

> The current code gives the result...
>
> 0
> 1
> 2
> 3
> Traceback (most recent call last):
>   File "test2.py", line 17, in ?
>     print b.next ()
> StopIteration
>
> The output I want is...
>
> 0
> 1
> 2
> 3
> 2
> 3
>
> Obviously I need a deep copy - the shallow copies achieved by slices
> on lists etc would not preserve the entire state of the generator.

Steve, you can't even get a "deep copy" of an xrange object in isolation --
and the state of a local xrange object is part of your generator's state.
See my earlier reply for more on that.

> Is there any way to do this? Even a definite no would save me worrying
> about it.

definite-no-ly y'rs  - tim





More information about the Python-list mailing list