Screwing Up looping in Generator

Deborah Swanson python at deborahswanson.net
Tue Jan 3 20:01:18 EST 2017


Erik wrote, on January 03, 2017 3:45 PM
> 
> Hi,
> 
> On 03/01/17 22:14, Deborah Swanson wrote:
> > ...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)
> 
> What you have done there is taken an understanding of the underlying 
> machinery that allows the 'for' loop to be syntactic sugar over any 
> iterable and spelled it out, instead of just using 'for'! Without all 
> that, your example is:
> 
> for file in rootobs():
>    base = os.path.basename(file.name)
>    .
>    .
>    .
>    (etc)
> 
> [In fact, the machinery would also cope with the return value from 
> rootobs() being an iterable but not an iterator by using "files = 
> iter(rootobjs)"].
> 
> 
> 
> You seem to be reading up on how the stuff works under the 
> covers (i.e., 
> from the point of view of an implementer of a class or 
> library) and then 
> suggesting that that's what the *caller* of that class or 
> library needs 
> to do. They don't - for a caller, 'for x in seq:' is all they need to 
> know - the mechanics are handled by the interpreter coupled with the 
> dunder methods that the class may implement.
> 
> 
> E.

Ok, I'm in complete agreement with everything you said up to the last
paragraph, which I don't disagree with, I just don't see your point.

If you've read my last few posts you'll have seen me acknowledging that
normally a for loop is used, but a while and break on StopIteration is a
method that's useful when the output of the generator is unknown.

I haven't read through much documentation on generators, but I have
taken a course from MIT, in which a Computer Science professor gave us
several methods for working with generators, of which the while and
break on StopIteration method is one.  The original poster wanted to use
a while, and seemed to be saying he didn't know how many files the
generator he has would yield, so that was why I recommended the while
loop. Normally I would use a for loop too.
D.



More information about the Python-list mailing list