A question about generators

Richard J. Kuhns rjk at grauel.com
Mon Mar 18 11:34:49 EST 2002


I'm a relative newbie with python, so please be gentle.

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?

My specific application (I'm using SWIG to generate an interface to a
third-party binary-only library, so I have to use the API as is) is
approximately as follows (pretend we're looking through a sorted flat text
file):
1) Select a starting point.  For this particular instance, selecting the
starting point won't necessarily involve an exact match with whatever was
supplied as an argument.
2) Iterate through the file one line at a time until we either find
something interesting or hit the end of the file.
3) Do it all again with a different starting point.

I realize that there are several ways to write the loop I just described,
but I'd like to be able to use a single API for all searches, something
like this:

while 1:
    inkey = raw_input('Well? ')
    # there are also several variants like 'generate_exact_matches'
    for i in generate_appox_matches(inkey):
        if this_is_interesting(i):
            do_work(i)
        break

There's an assumption that if we find anything with the comparable
generate_exact_matches(), they're all interesting.

Should I just keep a variable around that keeps the last value of inkey and
compare them inside the generator each time?  That'll make the generator
code a lot more convoluted. There are several different calls to library
functions that may return a potentially interesting value, but it's
possible.

Any style suggestions will be greatly appreciated.

        - Rich
-- 
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