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

Stephen Horne steve at lurking.demon.co.uk
Sun Jul 22 00:43:56 EDT 2001


On Sat, 21 Jul 2001 17:41:54 -0400, "Tim Peters" <tim.one at home.com>
wrote:

>It's not at all clear what p.copy() "should" do, though-- even for simple
>iterators --and that's why we're leaving it out, at least at the start.  For
>example, the bindings of local variables are part of a generator's state.
>What should p.copy() do about *them*?  If a local vrbl is also a generator,
>should it (recursively) apply the .copy() method to it too?  Just make
>another reference to the current bindings of the locals?  Systematically do
>shallow copies of values?  Systematically do deep copies?

It's all *very* clear to me - only a full deep copy would do. The only
reason it should generate a different sequence to the original copy
would be due to external state.

I can see that a generator following exactly the same sequence again
is not much use, and that re-running the sequence should mean getting
a different result, but that should result from external state in my
mind - if only *some* internal state was copied, it would be far too
confusing.

However, although it would be an interesting capability, I'm not
actually sure my original thought was valid...

>> A major use I could think of for this is in applications that need to
>> balance searching by depth and by breadth according to some heuristic.
>> In addition to the search tree so far, it would be easy to record
>> generator states that have only identified some of the branches from a
>> particular state - so you could explore this area of the tree
>> depth-wise for a bit then nip-back to expand the breadth later. An
>> obvious application would be for board games such as chess.

Chess doesn't need to rederive from the same generator state more than
once - the tree building/searching heuristic I mentioned merely needs
to store a partially evaluated generator for each node that is capable
of working out the remaining possible moves from its state. Evaluating
the same position and move more than once would be pointless.

Given that, I'm not sure I can think of another use. Backtracking in
the Icon sense can be handled quite effectively without it.

>Needs a PEP, and won't go in for 2.2 because I can pretty much guarantee
>"one size fits all" won't.  Python generators aren't quite like any other
>language's, and so we need more real-life experience with them before
>deciding what (if anything) more is truly needed.

I can accept that.

>in-the-meantime-python-chess-apps-aren't-really-a-major-use<wink>-ly

Of course you're right - noughts and crosses is *much* more important
;-)




More information about the Python-list mailing list