PEP on breaking outer loops with StopIteration
nwinters3000 at gmail.com
nwinters3000 at gmail.com
Tue Jun 10 09:47:13 EDT 2008
On Jun 9, 10:50 pm, Dan Bishop <danb... at yahoo.com> wrote:
> On Jun 9, 8:07 pm, "Kris Kowal" <kris.ko... at cixar.com> wrote:
>
> > I had a thought that might be pepworthy. Might we be able to break
> > outer loops using an iter-instance specific StopIteration type?
>
>
> You can break out of outer loops now with the proper (ab)use of
> exceptions:
>
> class BreakInner(Exception):
> pass
> class BreakOuter(Exception):
> pass
> try:
> for letter in string.lowercase:
> try:
> for number in xrange(10):
> print letter, number
> if letter == 'a' and number == 5:
> raise BreakInner()
> if letter == 'b' and number == 5:
> raise BreakOuter()
> except BreakInner:
> pass
> except BreakOuter:
> pass
I prefer having a new function wrapping the inner loop and using both
break and return, but this doesn't allow you to "break 1 loop up and 2
loops up", and doesn't help to continue a particular loop further up
def innerLoop(letter):
for number in xrange(10):
print letter, number
if letter == 'a' and number == 5:
break
if letter == 'b' and number == 5:
return
for letter in string.lowercase:
innerLoop(letter)
In response to the suggested syntax, I have found occasions where I
iterate through the same variable [say searching for duplicates within
some tolerance to merge into one item] in an inner loop. I also don't
see how it would extend to something like:
for evenNumber in [x*2+1 for x in xrange(5)]: print evenNumber
More information about the Python-list
mailing list