[Python-ideas] possible extension to how the new StopIteration is handled (python >=3.3)

Stephan Sahm Stephan.Sahm at gmx.de
Thu Oct 2 19:39:21 CEST 2014


Hi all,

I just tried the new possibilities in writing generators which were
included since python3.3 into the python standard.

Concretely, using return 1  in a generator is equal to raise
StopIteration(1)
Thus the following works:

>>> def f():

...     yield 0

...     return 1

>>> g = f()
>>> next(g)
0

>>> next(g)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration: 1

however calling next(g) once again gives the following:

>>> next(g)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration


mind the missing StopIteration: 1 . In my impression this is not like I
intuitively think about a generator. If there is a StopIteration Exception
connected to a generator, then there should be only ONE such.

This is not only theoretical, but would have a real application using such
generator in for loops. At the moment the following happens:

>>> g = f()

>>> for e in g:
...     print(e)
...
0
>>> next(g)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration


Remind again the missing StopIteration: 1 .   If the same StopIteration
would be thrown at every call when g is empty, one could actually extract
the return value (without using some maybe possible but more
complicated return_value
= yield from  work arrounds).


Any feedbacks?
Are there others thinking that this would be a straightforward extension to
the newly introduced raise StopIteration(return_value) feature?



looking forward to your responses,
with best wishes,

Stephan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20141002/1888afd0/attachment.html>


More information about the Python-ideas mailing list