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

Stephen Horne steve at lurking.demon.co.uk
Sat Jul 21 17:51:13 EDT 2001


I don't seem to be getting much response. Please help!!!

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.

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.

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




More information about the Python-list mailing list