My Generator Paradox!
Ron Adam
rrr at ronadam.com
Sat Mar 18 00:55:39 EST 2006
vbgunz wrote:
> OK. I hope my understanding of the yield keyword and generators in a
> general sense are now better understood. When a generator function is
> assigned to an identifier, no code is executed and a generator is
> immediately returned. When the next() method is called on the new
> generator, code from top to bottom executes within the generator until
> it reaches it's first yield. Many yields can appear within one
> generator. When this is the case a next method call will execute code
> from yield to yield. Code that appears in a loop after a yield keyword
> is executed on the next() method call.
>
> I hope I got it right. I love you guys for your patience and examples.
> It is greatly appreciated and means very much to me! Thank you fellas!
Yep, looks like you have it. ;-)
Only need to add what happens if a generator exits the end after the
yield(s).
If it were a function it would return a None object even if it didn't
have a return at the end. But a generator raises a StopIteration
Exception.
>>> def gen():
... yield 'hello'
... print 'all done'
...
>>> g = gen()
>>> g.next()
'hello'
>>> g.next()
all done
Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration
This is the signal to indicate iteration is finished. You don't see it
when you are using generators as iterators because it's usually caught
by the object or statement using the generator.
Cheers,
Ron
More information about the Python-list
mailing list