A question about generators

Richard J Kuhns rjk at grauel.com
Wed Mar 20 20:52:39 EST 2002


David Eppstein <eppstein at ics.uci.edu> writes:

> In article <mailman.1016494109.20996.python-list at python.org>,
>  "Delaney, Timothy" <tdelaney at avaya.com> wrote:
> 
> > > I have an application where I think either an iterator or a 
> > > generator would
> > > be ideal, but I have to be able to reset whichever I use.  The paper
> > > "What's New in Python 2.2" says that there's no way to reset 
> > > an iterator,
> > > so that's out.  Is there a straight-forward way to reset a generator,
> > > though?
> > 
> > That's not actually correct. There is no general way to reset and iterator
> > or generator, but you can make a custom iterator or generator that can be
> > reset.
> 
> You could create the generator inside some larger scope, and communicate 
> with it by changing variables in that scope.  Ok, actually it's not 
> possible to change a variable from outside that variable's scope (why??) 
> but it is possible to have a list or dictionary within a scope and 
> change one of its cells.
> 

That's pretty much what I ended up doing -- I put a "while 1:" loop around
the rest of the code in the generator, and I test a "reset generator"
variable after each yield.  If it's set, "continue" the while loop. It's
kind of nasty-looking, but it seems to work.  It's one of those things that
won't be used very often, but when I need it I REALLY need it.

Thanks for the comments.
-- 
Richard Kuhns			rjk at grauel.com
PO Box 6249			Tel: (765)477-6000 \
100 Sawmill Road				    x319
Lafayette, IN  47903		     (800)489-4891 /

______________________________________________________________________
Posted Via Uncensored-News.Com - Still Only $9.95 - http://www.uncensored-news.com
   With NINE Servers In California And Texas - The Worlds Uncensored News Source
  



More information about the Python-list mailing list