My Generator Paradox!

Ron Adam rrr at ronadam.com
Fri Mar 17 17:30:38 EST 2006


Robert Kern wrote:
> 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.
> 

Maybe this will clarify it further.


 >>> def gen(n):
...   while 1:
...     print 'before yield'
...     yield n
...     print 'after yield'
...
 >>> g = gen('hello')
 >>> g.next()
before yield
'hello'
 >>> g.next()
after yield
before yield
'hello'
 >>> g.next()
after yield
before yield
'hello'

When the next() method is called the generator runs until it reaches a 
yield.  At which point it's rests until the next() method is called again.

Although there are times when I wish it could run (as a thread) until it 
reaches a yield and then continue after the next() method is called 
until it reaches the next yield.

Cheers,
    Ron














More information about the Python-list mailing list