[Python-ideas] PEP 479: Change StopIteration handling inside generators
Steven D'Aprano
steve at pearwood.info
Wed Nov 19 02:15:48 CET 2014
On Wed, Nov 19, 2014 at 10:08:29AM +1100, Chris Angelico wrote:
> On Wed, Nov 19, 2014 at 9:54 AM, Terry Reedy <tjreedy at udel.edu> wrote:
> > On 11/18/2014 12:40 PM, Wolfgang Maier wrote:
> >
> >> 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)
> >
> >
> > I believe I thought then that one should write the explicit loop rather than
> > overload the 'comprehension' concept.
>
> I'm not sure about that. Comprehensions can already be filtered; is it
> such a jump from there to a "filter" that aborts on a certain
> condition? It may not be language-supported, but I don't see that it's
> illogical;
It certainly isn't. It's an obvious extension to the concept: terminate
the loop rather than filter it. At least two languages support early
termination:
http://clojuredocs.org/clojure_core/clojure.core/for
http://docs.racket-lang.org/guide/for.html
and it keeps getting asked for:
http://www.reddit.com/r/Python/comments/ciec3/is_there_anything_like_a_list_comprehension/
http://stackoverflow.com/questions/5505891/using-while-in-list-comprehension-or-generator-expressions
http://stackoverflow.com/questions/16931214/short-circuiting-list-comprehensions
https://www.daniweb.com/software-development/python/threads/293381/break-a-list-comprehension
https://mail.python.org/pipermail/python-ideas/2014-February/026036.html
https://mail.python.org/pipermail/python-ideas/2013-January/018969.html
There's a rejected PEP:
https://www.python.org/dev/peps/pep-3142/
and alternative solutions (write an explicit generator function, use
itertools.takewhile). So there's obviously a need for this sort of
thing, and (expr for x in iterable if cond() or stop()) seems to be a
common solution.
I'm not sure if that's a neat trick or a deplorable hack :-) but either
way this PEP will break code using it.
> and any use of a loop that appends to a list is rightly
> considered code smell.
I'm afraid I don't understand that comment. Why is appending to a list
inside a loop a code smell? That's exactly what list comps do.
--
Steven
More information about the Python-ideas
mailing list