My Generator Paradox!

Robert Kern robert.kern at gmail.com
Fri Mar 17 22:22:03 CET 2006


vbgunz wrote:
> I believe I understand now. the yield keyword is sort of like a cousin
> to return. return will bring back an object I can work with and so does
> yield *but* yield's object will most likely support the .next() method.

No, that's not really how it works. When a generator function is called, it
returns the generator object immediately. None of the code inside is executed.
Every time you call that generator function, you get a new generator object with
the initial state. The objects that are yielded inside the code don't show up yet.

The code inside the generator gets executed only when the generator object is
iterated over (or its .next() method is called). The objects that are yielded
are the results of calling the .next() method.

-- 
Robert Kern
robert.kern at gmail.com

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco




More information about the Python-list mailing list