Calling a generator multiple times

Bruce Eckel Bruce at
Sun Dec 9 03:09:32 CET 2001

On 12/9/01 at 12:14 AM Alex Martelli wrote:

>Bruce Eckel wrote:
>        ...
>> I believe that this is too restrictive a definition. My
>> of generators (from C++/STL) is that a generator is simply a
>> callable entity that returns an object every time you call it;
>> call takes no arguments so it is "generating" objects rather
> a Python generator such as:
>def imageneratorhonest(sequence1, sequence2):
>    for item in sequence1: yield item
>    for item in sequence2: yield item
>isn't a generator...?  

Exactly! It's actually the factory that creates the generator! The
code makes my point:

from __future__ import generators

def gen():
  while 1:
    yield 'spam'
g = gen()
print g
for i in range(5):

This produces:  
<generator object at 0x00792FE0>

'g' is the generator object, and when you call next() (which takes
no arguments, as I asserted), you get objects popping out. It's a
generator in exactly the sense that I described (perhaps not so
clearly): you don't give it any arguments when you call it, so it's
creating using some internal algorithm. The factory that creates
the generator can take arguments for its initialization. This is
just like creating a generator class that has a constructor that
probably takes arguments, and then using an object of that class
with some kind of argument-less call to create the objects. It's
just slicker using yield.

Most current information can be found at:
Bruce Eckel
Contains free electronic books: "Thinking in Java 2e" & "Thinking
in C++ 2e"
Please subscribe to my free newsletter -- just send any email to:
join-eckel-oo-programming at
My schedule can be found at:

More information about the Python-list mailing list