[Python-ideas] FW: Map-then-filter in comprehensions
Allan Clark
allan.clark at gmail.com
Tue Mar 8 11:04:34 EST 2016
On 8 March 2016 at 15:20, Chris Angelico <rosuav at gmail.com> wrote:
> 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.
>
>
Yes I certainly agree that this kind of extra syntax should not use a new
keyword.
> 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
>
>
I have to agree that I'm not mad-keen on the syntax I proposed either, I
just couldn't come up with an elegant alternative, and I guess I hoped
someone else might be.
> 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 _]
>
>
If I were introducing a new clause, I would probably suggest 'where' from
Haskell, which would allow multiple definitions perhaps. I'm not sure, I
guess there are two questions, 1) is this a need that should be addressed
at all, and 2) if so, what is the right syntax extension. I think it more
important to answer 1 and then the syntax-related endless threads can be
commenced. ;) Although of course the answer to 1 might be "only if someone
proposes an especially elegant syntax".
> 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.
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160308/ff504269/attachment.html>
More information about the Python-ideas
mailing list