generator with subfunction calling yield
Rob Williscroft
rtw at freenet.co.uk
Wed Sep 27 19:26:29 EDT 2006
wrote in news:1159396746.073994.28680 at h48g2000cwc.googlegroups.com in
comp.lang.python:
> Any insight?
>From the docs:
<quote>
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.
</quote>
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.
Rob.
--
http://www.victim-prime.dsl.pipex.com/
More information about the Python-list
mailing list