[issue31156] Stopiteration terminates while-loop

New submission from Günter Rote: It should be mentioned in the documentation that A StopIteration exception raised in the body of a while loop will terminate (and is caught by) the while-loop, thus leading to graceful termination. A good place would be here: 1) https://docs.python.org/3/reference/compound_stmts.html#the-while-statement I don't know how such a StopIteration termination of a while loop affects the else-clause. This should be clarified. Here: 2) https://docs.python.org/3/library/exceptions.html#StopIteration it would be good to explicitly state: An enclosing while-loop or for-loop acts like an implicit catch for StopIteration. The StopIteration exception will terminate the loop. (I guess, a for-loop is also just terminated when the StopIteration originates in the BODY of the loop, although this is not the typical case.) ---------- assignee: docs@python components: Documentation messages: 299982 nosy: Günter Rote, docs@python priority: normal severity: normal status: open title: Stopiteration terminates while-loop type: enhancement versions: Python 3.6 _______________________________________ Python tracker <report@bugs.python.org> <http://bugs.python.org/issue31156> _______________________________________

R. David Murray added the comment:
while True: ... raise StopIteration ... Traceback (most recent call last): File "<stdin>", line 2, in <module> StopIteration
---------- nosy: +r.david.murray _______________________________________ Python tracker <report@bugs.python.org> <http://bugs.python.org/issue31156> _______________________________________

Günter Rote added the comment: Sorry, that was my misinterpretation of what happened. I had been stumbling over an old program I had written, but apparently it works because the while-loop is inside a generator function, and the StopIteration is simply passed on. Here is a small demonstration example:
def f(): ... for x in range(5): ... yield x ... def g(): ... h=f() ... while True: ... yield next(h)+100 ... yield next(h) ... list(g()) [100, 1, 102, 3, 104]
(I am beginning to wonder whether this program will be adversely affected by PEP 479 -- Change StopIteration handling inside generators.) ---------- stage: -> resolved status: open -> closed versions: +Python 3.4 -Python 3.6 _______________________________________ Python tracker <report@bugs.python.org> <http://bugs.python.org/issue31156> _______________________________________
participants (2)
-
Günter Rote
-
R. David Murray