[Python-ideas] FW: Map-then-filter in comprehensions

Chris Angelico rosuav at gmail.com
Tue Mar 8 10:20:37 EST 2016


On Wed, Mar 9, 2016 at 1:59 AM, Émanuel Barry <vgr255 at live.ca> wrote:
> I’m going be confused by what sort of name binding it does. A quick glance
> at the keywords list tells me that no currently-existing keyword is “the
> obvious choice” for this purpose. I don’t think such a small niche warrants
> a new keyword, either.

Maybe a pseudo-keyword would be sufficient - comprehension/genexp
syntax is pretty solidly specified, so it's less likely to break stuff
than in general syntax.

I'm really not liking the proposed syntax, but maybe there's an
alternative. My first thought on reading this proposal is: "Ah, it's
like SQL's 'HAVING' keyword". The trouble is that SQL can identify its
columns, but Python doesn't have an easy syntax for "the thing you're
about to return". Something like:

[abs(x) for x in numbers having _ > 5]

The semantics would be equivalent to:
def <listcomp>():
    result = []
    for x in numbers:
        _ = abs(x)
        if _ > 5: result.append(_)
    return result

A 'having' clause (and, by the way, I'm not too enthused about the
name, but I'm using it as a placeholder because of SQL's use) would
have to go after all 'for' and 'if' clauses, and would have access to
one special name (maybe _ because of its use in interactive mode, or
maybe something else) which holds the value that would be returned. A
simple filter-out-the-false-ones could do this:

[regex.match(line) for line in lines having _]

Of course, people could just switch from 'if' to 'having' across the
board, but this has the same consequences that it does in SQL: now
*every* row has to be fully processed, only to be discarded at the
last step. Using 'having' with no underscore would violate common
sense and good style.

ChrisA


More information about the Python-ideas mailing list