PEP 255: Simple Generators

David Eppstein eppstein at ics.uci.edu
Wed Jun 20 14:42:08 EDT 2001


I'm wondering if it wouldn't make sense to allow a non-empty return 
statement in a generator, with the semantics that the object being returned 
is itself some kind of iterator that is used to continue the sequence.

i.e.
    def integers(i):
        yield i
        return integers(i+1)

...thus allowing a more functional-programming-like lazy iteration.
There would thus also be very little difference between a function that 
returns an iterator, and a generator that does some yields before returning 
an iterator.

Of course you could rewrite this particular example by wrapping a loop 
around the body, and in general you could simulate the same behavior with 
another loop in place of the return stmt:

    def integers(i):
        yield i
        for j in integers(i+1):
            yield j

But, that adds an unnecessary middleman in the implementation, and looks 
uglier.

(Disclaimer, I haven't read all previous discussions on the subject, quite 
likely someone else has already proposed this and been shot down, in which 
case I'd appreciate a pointer to the refutation.)
-- 
David Eppstein       UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/



More information about the Python-list mailing list