473,785 Members | 2,811 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 3523
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
1912
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
4415
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 efficient generator expressions on the fly: sum(x*x for x in roots)
9
2689
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 generators from outside (although it looks like it might be convenient in some cases), but being able...
8
2307
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
3047
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
1956
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 problem, though: In order to get random file access, the tokenizer should not simply spit out a series...
5
2255
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
1751
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 sequence: yield item
3
6937
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
9645
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10330
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10153
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10093
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9952
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7500
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5381
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2880
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.