Generator not generating

J

Jeff Lowery

Hi,

Although I'm no Python expert, I have written generators in the past
that have worked like a charm. Don't know why this one doesn't:


****
class App:
"""
A simple Tk application that plots random lines
"""

def __init__(self, master):
# create the main frame
frame = Frame(master)
frame.pack()

# create a canvas within the frame
self.canvas = Canvas(frame, width=400, height=400)
self.canvas.pack(side=TOP)

# create a button below the canvas and within the frame
# method add_line() is invoked if the button is clicked
button = Button(frame, text="Plot",
command=self.plot_dist)
button.pack(side=BOTTOM)

def plot_dist(self):
file = None;

file = nextFile().next() # call to generator here
...

def nextFile():
dirPath = 'C:/somedir'
file = None;

for filename in os.listdir(dirPath):
file = open(dirPath + '/' + filename, 'r')
yield file


#
# MAIN
#
# Initialize the graphical toolkit
root = Tk()

# Create the sample graphical application
app = App(root)

# Use in stand-alone programs, not in IDLE
root.mainloop()

****

I trace through this in the debugger and the call to nextFile().next()
always starts at the beginning of the function (it always returns the
first file in C:/somedir).

So what stoopid mistake am I overlooking here? I am running v2.3, BTW.
 
C

Christopher T King

def plot_dist(self):
file = None;

file = nextFile().next() # call to generator here

****

I trace through this in the debugger and the call to nextFile().next()
always starts at the beginning of the function (it always returns the
first file in C:/somedir).

That's because your code restarts the generator each time ;)

When a generator function is called, it returns a new generator object
that starts from the beginning of the function that can then be iterated
over. To get the effect you want, you should call the generator only
once, and then store its value away for future use:

def __init__(self, master):
self.files = nextFile()

def plot_dist(self):
file = self.files.next() # call to generator here

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top