Screwing Up looping in Generator

Deborah Swanson python at deborahswanson.net
Mon Jan 2 21:14:50 EST 2017


Terry Reedy
>
> On 1/3/2017 3:53 PM, Deborah Swanson wrote:
>
> >> I think you're expecting
> >>
> >>    for file in rootobs
> >>
> >> to get the next yield for you from rootobs, but unless someone
> >> corrects me, I don't think you can expect a 'for' statement to do
> >> that. You need to have a 'next' statement inside your for
> loop to get
> >> the next yield from the generator.
>
> As I read this, out of context, it is wrong.  It it very
> unusual to call
> next on the current iterator (here next(rootobs)), inside a for loop.
>
> > You probably want something like :
> >
> > for f in rootobs:
> >     file = next
>
> This is definitely wrong, as it makes 'find' an alias for the next()
> function.
>
> >     base = os.path.basename(file.name)
>
> and file.name will be an AttributeError.
>
> ---
> If one wants to iterate through files and lines within files, which I
> believe I saw in this thread, one should have a for loop
> within a for loop.
>
> --
> Terry Jan Reedy

Yes, my first attempts were screwups. I didn't remember generator usage 
correctly, but I believe my last answer was correct:

...you have to create the generator object first and use it to call the next 
function. And I really don't think you can use a generator as your range in a 
for loop. So I'd use a 'while True', and break out of the loop when you hit the 
StopIteration exception:

files = rootobs()

while True:
  try:
    file = files.next()
  except StopIteration:
    break

    base = os.path.basename(file.name)
       .
       .
       .
      (etc)



More information about the Python-list mailing list