Help with generators outside of loops.

Andrea Griffini agriff at tin.it
Wed Dec 8 09:03:47 CET 2004


David Eppstein wrote:
> In article <mailman.7340.1102463745.5135.python-list at python.org>,
>  "Robert Brewer" <fumanchu at amor.org> 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.

Isn't the handling of StopIteration confined in the very moment of
calling .next() ? This was what I expected... and from a simple test
looks also what is happening...

 >>> for x in xrange(10):
	if x == 8:
		raise StopIteration()
	print x

	
0
1
2
3
4
5
6
7

Traceback (most recent call last):
   File "<pyshell#7>", line 3, in -toplevel-
     raise StopIteration()
StopIteration


i.e. the loop didn't stop silently

Andrea



More information about the Python-list mailing list