Screwing Up looping in Generator

Erik python at lucidity.plus.com
Tue Jan 3 08:25:38 EST 2017


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.



More information about the Python-list mailing list