Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Iterator class to allow self-restarting generator expressions?

Reply
Thread Tools

Iterator class to allow self-restarting generator expressions?

 
 
John O'Hagan
Guest
Posts: n/a
 
      03-01-2009
Inspired by some recent threads here about using classes to extend the
behaviour of iterators, I'm trying to replace some some top-level functions
aimed at doing such things with a class.

So far it's got a test for emptiness, a non-consuming peek-ahead method, and
an extended next() which can return slices as well as the normal mode, but
one thing I'm having a little trouble with is getting generator expressions
to restart when exhausted. This code works for generator functions:

class Regen(object):
"""Optionally restart generator functions"""
def __init__(self, generator, options=None, restart=False):
self.gen = generator
self.options = options
self.gen_call = generator(options)
self.restart = restart

def __iter__(self):
return (self)

def next(self):
try:
return self.gen_call.next()
except StopIteration:
if self.restart:
self.gen_call = self.generator(self.options)
return self.gen_call.next()
else:
raise

used like this:

def gen():
for i in range(3):
yield i

reg = Regen(gen, restart=True)

I'd like to do the same for generator expressions, something like:

genexp = (i for i in range(3))

regenexp = Regen(genexp, restart=True)

such that regenexp would behave like reg, i.e. restart when exhausted (and
would only raise StopIteration if it's actually empty). However because
generator expressions aren't callable, the above approach won't work.

I suppose I could convert expressions to functions like:

def gen():
genexp = (i for i in range(3))
for j in genexp:
yield j

but that seems tautological.

Any clues or comments appreciated.

John

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
newbie: allow deny vs deny allow Jeff ASP .Net 2 09-19-2006 02:12 AM
Difference between Java iterator and iterator in Gang of Four Hendrik Maryns Java 18 12-22-2005 05:14 AM
How to convert from std::list<T*>::iterator to std::list<const T*>::iterator? PengYu.UT@gmail.com C++ 6 10-30-2005 03:31 AM
Location element in the Web.config file. Allow System Admin whole directory, allow others specific page Ryan Taylor ASP .Net Security 1 09-09-2004 06:52 PM
Iterator doubts, Decision on Iterator usage greg C++ 6 07-17-2003 01:26 PM



Advertisments