Generator not generating

Jeff Lowery J.Lowery at
Fri Jul 23 18:20:15 CEST 2004

Wow, that make sense but somehow I've managed to (ab)use generators
several times like this before and (by luck) avoided the problem.  For
example, the previous one I wrote did file.readline(), so the generator
worked because the file pointer was incremented. No such thing as a
directory pointer, I guess =^P

Thanks. Now if I can only break my bad habits...

-----Original Message-----
From: at
[ at] On Behalf Of
Christopher T King
Sent: Thursday, July 22, 2004 5:52 PM
To: python-list at
Subject: Re: Generator not generating

On Thu, 22 Jul 2004, Jeff Lowery wrote:

>     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 =  # call to generator here

Hope this helps.


More information about the Python-list mailing list