Calling a generator multiple times

James_Althoff at i2.com James_Althoff at i2.com
Mon Dec 10 13:17:01 EST 2001


<Jim> responding to <Bruce> responding to <Jim>

I was describing only Python's current "simple generators"
(as that is what I thought the discussion was about).

Jim

===============================================

>So as to not confuse myself, I think of generators thusly:
>
>A generator is a function or method that -- by virtue of using the
yield
>statement -- *creates* and *returns* an iterator object when
invoked by a
>caller.  The caller normally takes that returned iterator object
and uses
>it by invoking its "next" method until StopIteration is raised.
The code
>inside the generator function or method *runs* when the "next"
method of
>said iterator is invoked.  Each time a caller invokes the
*generator*
>function or method, a new iterator object is created and returned.

I believe that this is too restrictive a definition. My experience
of generators (from C++/STL) is that a generator is simply a
callable entity that returns an object every time you call it; this
call takes no arguments so it is "generating" objects rather than
being a factory -- factory calls take arguments and build the
object based on those arguments while generators create new objects
based on some internal logic. So a generator could be thought of as
a zero-argument factory.

I think it might have been better to say that Python now has
"improved support for generators" in the form of 'yeild.' I suspect
there will be a fair amount of discussion for awhile, every time
the term "generator" is used, if the accompanying code does not
include 'yeild'.

I also think that a generator only returns an iterator if that's
what it promises to generate; otherwise it returns a regular object.

Most current information can be found at:
http://www.mindview.net/Etc/notes.html
===================
Bruce Eckel    http://www.BruceEckel.com
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 earth.lyris.net
My schedule can be found at:
http://www.mindview.net/Calendar
===================



--
http://mail.python.org/mailman/listinfo/python-list






More information about the Python-list mailing list