generator with subfunction calling yield

Rob Williscroft rtw at
Thu Sep 28 01:26:29 CEST 2006

 wrote in news:1159396746.073994.28680 at in 

> Any insight?

>From the docs:

The yield statement is only used when defining a generator function, and is 
only used in the body of the generator function. Using a yield statement in 
a function definition is sufficient to cause that definition to create a 
generator function instead of a normal function. 

Note that its when a function defention contains a yeild statement 
(expression) that the defenition is taken to be a generator function.

> def nn():
>    def _nn():
>        print 'inside'
>        yield 1
>    print 'before'
>    _nn()
>    print 'after'

So tha above (nn()) isn't a generator as it doesn't contain a 
yield statement.

Note also that the call to _nn() returns a generator, it isn't a
regular function call.

Here is nn() re-writen to return what you may have originaly expected:

def nn():
    def _nn():
        print 'inside'
        yield 1

    print 'before'

    for i in _nn():
      yield i

    print 'after'

So to forward another generator you need to iterate over it and
yield each element, just as you would for any other iterable.


More information about the Python-list mailing list