Title: Stopiteration terminates while-loop
Type: enhancement Stage: resolved
Components: Documentation Versions: Python 3.4
Status: closed Resolution:
Dependencies: Superseder:
Assigned To: docs@python Nosy List: Günter Rote, docs@python, r.david.murray
Priority: normal Keywords:

Created on 2017-08-09 09:49 by Günter Rote, last changed 2017-08-09 14:22 by Günter Rote. This issue is now closed.

Messages (3)
msg299982 - (view) Author: Günter Rote (Günter Rote) Date: 2017-08-09 09:49
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:

I don't know how such a StopIteration termination of a while loop
affects the else-clause. This should be clarified.

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.)
msg300005 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2017-08-09 13:37
>>> while True:
...     raise StopIteration
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
msg300011 - (view) Author: Günter Rote (Günter Rote) Date: 2017-08-09 14:22
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.)
Date User Action Args
2017-08-09 14:22:02Günter Rotesetstatus: open -> closed

stage: resolved
messages: + msg300011
versions: + Python 3.4, - Python 3.6
2017-08-09 13:37:54r.david.murraysetnosy: + r.david.murray
messages: + msg300005
2017-08-09 09:49:19Günter Rotecreate