generator with subfunction calling yield

James Stroud jstroud at mbi.ucla.edu
Wed Sep 27 19:18:42 EDT 2006


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
> 

In the commented line, you are only creating a generator. This is not 
equivalent to calling its "next" function, i.e., nothing will be 
"yielded" the way you have written it.


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

     print 'before'
     _nn()              # <== just makes a generator
     print 'after'

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list