Help with generators outside of loops.

David Eppstein eppstein at
Wed Dec 8 01:34:37 CET 2004

In article <mailman.7340.1102463745.5135.python-list at>,
 "Robert Brewer" <fumanchu at> wrote:

> > But I'm guessing that you can't index into a generator as if 
> > it is a list.
> row = obj.ExecSQLQuery(sql, args).next()

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.

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

More information about the Python-list mailing list