Generator not generating

James Henderson james at logicalprogression.net
Thu Jul 22 20:49:56 EDT 2004


Jeff Lowery wrote:

> 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.
> 

Hi Jeff,

Every time you call nextFile().next() you create a new generator. 
Perhaps you should add this line to the __init__() method (all untested):

   self.file_gen = nextFile()

and then in plot_dist():

   file = self.file_gen.next()

HTH,
James




More information about the Python-list mailing list