PEP on breaking outer loops with StopIteration

Diez B. Roggisch deets at nospam.web.de
Tue Jun 10 02:51:00 EDT 2008


Kris Kowal schrieb:
> 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()
> 
> The first StopIteration would halt the inner loop.  The second
> StopIteration would halt the outer loop.  The inner for-loop would
> note that the letters.StopIteration instance is specifically targeted
> at another iteration and raise it back up.

For the record: I share GvR's opinion on the general usefulness.

Additionally, your syntax is impossible. There isn't always a containing 
variable for the iterable.

And if you meant "letter", it's ambigous. It is perfectly legal in 
python to do this:

class Foo(object):
     StopIteration = StopIteration

for letter in [Foo(), Foo()]:
     for number in range(10):
         raise letter.StopIteration


Diez



More information about the Python-list mailing list