Enviando StopIteration a for loop desde fuera del iterador
Hay varias formas de salir de algunos bucles anidados
Son
1) para usar break-continue
for x in xrange(10):
for y in xrange(10):
print x*y
if x*y > 50:
break
else:
continue # only executed if break was not used
break
2) para usar return
def foo():
for x in range(10):
for y in range(10):
print x*y
if x*y > 50:
return
foo()
3) para usar una excepción especial
class BreakIt(Exception): pass
try:
for x in range(10):
for y in range(10):
print x*y
if x*y > 50:
raise BreakIt
except BreakIt:
pass
Pensé que podría haber alguna otra forma de hacerlo. Es mediante el uso de la excepción StopIteration enviada directamente al bucle externo. Escribí este código
it = iter(range(10))
for i in it:
for j in range(10):
if i*j == 20:
raise StopIteration
Desafortunadamente, StopIteration no había sido atrapado por ningún bucle for y ese código produjo un Traceback feo. Creo que es porque StopIteration no se envió desde el interior del iteradores. (esa es mi suposición, no estoy seguro de eso).
¿Hay alguna forma de enviar StopIteration al bucle externo?
¡Gracias