Screwing Up looping in Generator

Deborah Swanson python at deborahswanson.net
Tue Jan 3 01:40:14 EST 2017


Erik wrote, on January 03, 2017 5:26 PM
> Hi,
>
> On 04/01/17 01:12, Deborah Swanson wrote:
> > The main reason you might want to catch the StopIteration
> exception is
> > to do something else before your code simply stops running. If all
> > you're doing is run a generator til it's out of gas, and that's all
> > you want it to do, then there's no need to catch anything.
>
> Ah! OK, I see where the lines are being crossed now ;) Although
> StopIteration is an exception, it is something that the 'for/iter'
> machinery handles for you under the covers. Each 'for' statement
> effectively has a 'try' block around it that catches
> 'StopIteration' and
> just terminates that particular 'for' loop and continues on with the
> remainder of your script.
>
> Raising a 'StopIteration' is an internal mechanism used to determine
> when an iterator (i.e., the thing a 'for' loop is looping over) has
> exhausted itself. It's not something a regular user is ever
> expected to
> know about let alone catch.
>
> When execution falls out of the bottom of a generator,
> StopIteration is
> raise (compared to a regular function or method returning 'None').
>
> E.

Looks like those MIT professors knew what they were teaching us after all! 
Sneaky, but they never once hinted that this was any deep dark secret. Just a 
way to deal with generators that will stop after a finite and unknown number of 
yields, and you want your code to keep going after the generator quits. I 
thought I was just regurgitating a standard approach, and surprised to get so 
much push back on it.

Seems like python uses a lot of its external functionality (what we normally 
code with) for internal behavior too. In this case, and for empty returns, 
they're raising exceptions, catching them and then doing what they want to. I 
suppose, if you don't want the method returning None, you could catch that 
exception and return something else. Or return nothing at all, which is what I 
usually want to do when those pesky Nones crop up.  But I'm not entirely sure 
how you would make it return nothing at all.



More information about the Python-list mailing list