PEP on breaking outer loops with StopIteration
Dan Bishop
danb_83 at yahoo.com
Tue Jun 10 01:50:01 EDT 2008
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?
>
> This is the desired, if not desirable, syntax::
>
> import string
> letters = iter(string.lowercase)
> for letter in letters:
> for number in range(10):
> print letter, number
> if letter == 'a' and number == 5:
> raise StopIteration()
> if letter == 'b' and number == 5:
> raise letters.StopIteration()
>
You can break out of outer loops now with the proper (ab)use of
exceptions:
class BreakOuter(Exception):
pass
try:
for letter in string.lowercase:
for number in xrange(10):
print letter, number
if letter == 'a' and number == 5:
break
if letter == 'b' and number == 5:
raise BreakOuter()
except BreakOuter:
pass
Or, for consistency:
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
More information about the Python-list
mailing list