473,554 Members | 3,188 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

generator with subfunction calling yield

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

Sep 27 '06 #1
3 3511
an************* *@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/
Sep 27 '06 #2
wrote in news:11******** *************@h 48g2000cwc.goog legroups.com in
comp.lang.pytho n:
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/
Sep 27 '06 #3
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

an************* *@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
Sep 27 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1898
by: TheDustbustr | last post by:
<code> from __future__ import generators from time import time threads= def sleep(n): print "In Sleep" t=time() while (t+n>time()): yield None
72
4349
by: Raymond Hettinger | last post by:
Peter Norvig's creative thinking triggered renewed interest in PEP 289. That led to a number of contributors helping to re-work the pep details into a form that has been well received on the python-dev list: http://www.python.org/peps/pep-0289.html In brief, the PEP proposes a list comprehension style syntax for creating fast, memory...
9
2672
by: Francis Avila | last post by:
A little annoyed one day that I couldn't use the statefulness of generators as "resumable functions", I came across Hettinger's PEP 288 (http://www.python.org/peps/pep-0288.html, still listed as open, even though it's at least a year old and Guido doesn't seem very hot on the idea). I'm not too sure of its ideas on raising exceptions in...
8
2295
by: Paul Chiusano | last post by:
I've been playing around with generators and have run into a difficulty. Suppose I've defined a Node class like so: class Node: def __init__(self, data=None, left=None, right=None): self.children = self.children.append(left) self.children.append(right) self.data = data
45
2989
by: Joh | last post by:
hello, i'm trying to understand how i could build following consecutive sets from a root one using generator : l = would like to produce : , , , ,
12
1926
by: Thomas Lotze | last post by:
Hi, I'm trying to figure out what is the most pythonic way to interact with a generator. The task I'm trying to accomplish is writing a PDF tokenizer, and I want to implement it as a Python generator. Suppose all the ugly details of toknizing PDF can be handled (such as embedded streams of arbitrary binary content). There remains one...
5
2239
by: Jerzy Karczmarczuk | last post by:
I thought that the following sequence gl=0 def gen(x): global gl gl=x yield x s=gen(1)
11
1724
by: vbgunz | last post by:
I am afraid that this is the first time in which I would probably need something explained to me as if I were a little child. I am having a hard time getting this through my thick skull. What in the world is wrong with this!? ''' ########################################################### ''' def generatorFunction(sequence=): for item in...
3
6916
by: Ehsan | last post by:
hi coulde any one show me the usage of "yield" keyword specially in this example: """Fibonacci sequences using generators This program is part of "Dive Into Python", a free Python book for experienced programmers. Visit http://diveintopython.org/ for the latest version.
0
7583
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7507
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7873
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5424
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5143
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3546
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1115
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
825
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.