Screwing Up looping in Generator

Erik python at
Tue Jan 3 06:44:50 EST 2017


On 03/01/17 22:14, Deborah Swanson wrote:
> 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 =
>   except StopIteration:
>     break
>     base = os.path.basename(
>        .
>        .
>        .
>       (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(

[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 


More information about the Python-list mailing list