Iterator class to allow self-restarting generator expressions?

Chris Rebert clp2 at
Sun Mar 1 18:51:07 CET 2009

On Sun, Mar 1, 2009 at 8:54 AM, Gabriel Genellina
<gagsl-py2 at> wrote:
> En Sun, 01 Mar 2009 13:20:28 -0200, John O'Hagan <research at>
> escribió:
>> 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:
> [...]
>> 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'm afraid you can't do that. There is no way of "cloning" a generator:

Really? What about itertools.tee()? Sounds like it'd do the job,
albeit with some caveats.


Follow the path of the Iguana...

More information about the Python-list mailing list