quick question about generator.next()

Tim Peters tim.one at comcast.net
Wed Sep 4 11:44:17 EDT 2002

[Erik Price]
> A quick question about generators:
> If I have a generator object, the first value produced by the generator
> object does not actually get produced until the first time I call
> generator_object.next() , correct?

Correct, although in the most frequent case you don't need to call .next()

    for object in some_generator_function(...):

Calls to next() are generated by "for" statements for iterable objects of
all kinds (generators, sequences, dicts, file objects, ... anything with an
__iter__ method).

> In other words, simply instantiating the generator object doesn't
> "activate" the generator function, rather it just creates it -- only
> when the next() method is called does the generator's internal logic
> "activate", right?

Partly; calling the generator function *does* do some real work, including
evaluating the actual arguments, and setting up the function's formal
arguments as initialized local variables.  The *body* of the generator
function is not entered at this time, though.

> (Where are generator objects getting their next() method from anyway...
> is it implicitly inherited behind the scenes when I use the "yield"
> keyword to turn a function into a generator?)

The PEP explains this.  A generator function returns a generator iterator,
and it's the latter that has a next() method.  A compile-time effect of
"yield" is to light a "hey, this function is a generator-function" flag bit
in the compiled code object.

More information about the Python-list mailing list