generator with subfunction calling yield
Matimus
mccredie at gmail.com
Wed Sep 27 19:32:52 EDT 2006
The issue is that nn() does not return an iterable object. _nn()
returns an iterable object but nothing is done with it. Either of the
following should work though:
def nn():
def _nn():
print 'inside'
yield 1
print 'before'
for i in _nn():
yield i
print 'after'
Or you could just return the iterable object that was returned by
_nn():
def nn():
def _nn():
print 'inside'
yield 1
print 'before'
retval = _nn():
print 'after'
return retval
For clarification, using yeild creates a generator. That generator
returns an iterable object. Nesting generators does not somehow
magically throw the values up the stack. I made the same mistake when I
first started messing with generators too.
-Matt
andy.leszczynski at gmail.com wrote:
> Hi,
>
> I might understand why this does not work, but I am not convinced it
> should not - following:
>
> def nnn():
> print 'inside'
> yield 1
>
> def nn():
> def _nn():
> print 'inside'
> yield 1
>
> print 'before'
> _nn()
> print 'after'
>
>
> for i in nnn():
> print i
>
> for i in nn():
> print i
>
>
>
> gives results:
>
> $ python f.py
> inside
> 1
> before
> after
> Traceback (most recent call last):
> File "f.py", line 18, in ?
> for i in nn():
> TypeError: iteration over non-sequence
>
> while I would expect:
> $ python f.py
> inside
> 1
> before
> inside
> 1
> after
>
> Any insight?
>
> andy
More information about the Python-list
mailing list