[Python-ideas] PEP 479: Change StopIteration handling inside generators
Wolfgang Maier
wolfgang.maier at biologie.uni-freiburg.de
Tue Nov 18 18:40:30 CET 2014
On 11/18/2014 05:50 AM, Guido van Rossum wrote:
>
> Separate from this special case, I am also worried about backward
> compatibility, and I have yet to get a good idea for how widespread code
> is that depends on StopIteration bubbling out from generators. I also
> don't have a good idea how often this issue bites users, but I have a
> feeling it does bite. E.g. this quote from c.l.py <http://c.l.py>
> (https://mail.python.org/pipermail/python-list/2014-November/680775.html):
>
> """
> I did find it annoying occasionally that raising StopIteration inside a
> generator expression conveys a different behavior than elsewhere. It did
> take me quite a while to understand why that is so, but after that it
> did not cause me much of a headache anymore.
> """
>
I just remembered one use of the current behavior. Two years ago or so,
I was suggesting on this list a possibility for early termination of
comprehensions when a particular value is encountered. In other words,
an equivalent to:
l = []
for x in seq:
if x == y:
break
l.append(x)
At the time, somebody suggested (roughly):
def stop():
raise StopIteration
l = list(x for x in seq if x!=y or stop())
which, for the very reasons discussed in this thread, works only as a
generator expression and not in comprehension form.
I used this solution in some not particularly important piece of code so
I wouldn't despair if it wasn't compatible with the next release of the
language.
Also, I have a feeling that some of you may consider this sort of a hack
in the first place.
Just thought I'd mention it here for completeness.
Wolfgang
More information about the Python-ideas
mailing list