Ron Adam wrote:
Maybe break should raise a StopIteration and continue should raise NextIteration?
The trouble with that is that semantically, right now, StopIteration gets caught only during the testing to see if the iteration should go for another loop around, not during the body of the loop. Here are some illustrations of the current behavior:
def blah():
... yield 1 ... raise StopIteration ... yield 2 ...
for x in blah():
... print(x) ... 1
As you can see, it silently swallows the StopIteration raised when evaluating the iterator produced by blah().
def blah():
... raise StopIteration ...
for x in blah():
... print("hi") ... Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in blah StopIteration
Above, the exception isn't swallowed, since blah() hadn't yet been evaluated, since it's a function, not a generator.
And if you try to use StopIteration like break, that just won't work:
for x in range(2):
... raise StopIteration ... Traceback (most recent call last): File "<stdin>", line 2, in <module> StopIteration
This is why if my proposal were accepted we would need three loop controlling exceptions: StopIteration, to halt the loop while fetching the next value; ContinueIteration, to simulate the behavior of continue; and BreakIteration, to simulate the behavior of break.
-- Carl