[Python-ideas] Is this PEP-able? for X in ListY while conditionZ:

Nick Coghlan ncoghlan at gmail.com
Thu Jun 27 10:43:07 CEST 2013


On 27 June 2013 17:28, Andrew Barnert <abarnert at yahoo.com> wrote:
> 8. Allow else break in comp_if clauses.
>
>     x = [value for value in iterable if pred(value) else break]
>
> This one is pretty easy to define rigorously, since it maps to exactly what the while attempt maps to with a slight change to the existing rules.
>
> But to me, it makes the code a confusing mess. I'm immediately reading "iterable if pred(value) else break", and that's wrong.

Ouch, I hadn't noticed that parallel. Yeah, it's a bad idea :)

Someone was asking earlier why I thought PEP 403 was at all relevant
to these discussions. It's because it makes it easy to define a one
shot generator function to precisely control the iterable in a
comprehension. If we assume a world where itertools.takewhile doesn't
exist, you could write an equivalent inline:

    @in x = [transform(value) for value in my_takewhile(pred, iterable)]
    def my_takewhile(pred, itr):
        for x in itr:
            if not pred(x):
                break
            yield x

All the important inputs are still visible in the header line, and the
definition of "takewhile" is right there, rather than sending the
reader off to another part of the code. It's an intermediate step
between "This callable needs to be a function or generator to get
access to full statement syntax, but we only use it in this one place"
and "This is a useful piece of independent functionality, let's make
it available as a function or method".

Would such syntax be a net win for a language? Highly arguable, which
is why the PEP is still deferred.

Cheers,
Nick.

--
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list