guarding for StopIteration (WAS: Help with generators outside of loops.)

David Eppstein eppstein at
Wed Dec 8 20:13:27 CET 2004

In article <62ztd.532216$D%.125153 at attbi_s51>,
 Steven Bethard <steven.bethard at> wrote:

> David Eppstein wrote:
> > I've made it a policy in my own code to always surround explicit calls 
> > to next() with try ... except StopIteration ... guards.
> > 
> > Otherwise if you don't guard the call and you get an unexpected 
> > exception from the next(), within a call chain that includes a for-loop 
> > over another generator, then that other for-loop will terminate without 
> > any error messages and the cause of its termination can be very 
> > difficult to track down.
> Just to clarify here, the only time code raising a StopIteration will 
> cause a for-loop to exit silently is if the StopIteration is raised in 
> an __iter__ method, e.g.:

Sure.  But in the situation I was attempting to describe, the __iter__ 
method calls the code of the outer generator, which (perhaps nested 
several levels deep) may call an inner generator.  In this case, the 
inner generator's StopIteration can terminate the outer loop.

David Eppstein
Computer Science Dept., Univ. of California, Irvine

More information about the Python-list mailing list