[Python-ideas] Assignments in list/generator expressions

Nick Coghlan ncoghlan at gmail.com
Mon Apr 11 04:58:00 CEST 2011


On Mon, Apr 11, 2011 at 11:42 AM, Eugene Toder <eltoder at gmail.com> wrote:
> I don't think it's fair to judge a feature by trying to imagine the
> worst misuse one can do with it. If you would do this consistently,
> you'd never introduce arrays (think code using arrays instead of
> classes, with magic undocumented indexes instead of attribute names)
> or dynamically-typed scripting languages (think Perl).
> Also, as pointed above, local assignment doesn't allow any more code
> written as comprehension than one can write now -- there are multiple
> work-arounds: repetition, nested comprehensions, for name in [expr].
> Local assignment simply provides a more direct way of doing it, and to
> me a more direct way is easier to read.

And we already have one kind of expression that owes its existence
almost entirely to the suboptimal workaround people were using to get
around the fact it wasn't available* :)

A "given/as" list comprehension subclause inspired by PEP 3150 might
actually be a more interesting idea to explore than I first thought
(considering that PEP 3150 itself is absolutely no help at all for
this particular use case).

That is, instead of having to choose one of the following 4
alternatives (and assorted variants of the explicit loop, such as
invoking list() on a generator function):

ys = [f(x) for x in xs if f(x)]
ys = [y for y in (f(x) for x in xs) if y]
ys = [y for x in xs for y in [f(x)] if y]

def _build_sequence(xs):
    ys = []
    for x in xs:
        y = f(x):
        if y:
            ys.append(y)
    return ys
ys = _build_sequence(xs)

The language could offer an "obvious" answer of the form:

ys = [y for x in xs given f(x) as y if y]

Multiple subexpressions would be handled gracefully via tuple
unpacking, and the translation to "long-form" Python code for actual
execution by the eval loop would follow the same style as is already
used for comprehensions and generator expressions (i.e. the last
alternative I listed above, with the details of the emitted code
changing appropriately based on the kind of comprehension).

So, despite my initial negative reaction, I'd now be interested in
reading a fully fleshed out PEP for this proposal.

Cheers,
Nick.

(*Read PEP 308 if the reference is unfamiliar)

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



More information about the Python-ideas mailing list