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

Mark Mollineaux bufordsharkley at gmail.com
Tue Mar 8 17:10:05 EST 2016


> Currently `_` is not a keyword or special in any way. How do we resolve
the ambiguity with:
> _ = 10
> [x for x in xs if _ > 10]

It's special within the REPL (referring to the last returned expression),
so it would at least have some precedence in python to be made special in
another (somewhat similar) context...

Too, there's already special scoping for list comprehensions.

> [(base//x) % 10 for x in numbers if x if _]
>
>The first one MUST be filtered prior to mapping (else you'll get a
ZeroDivisionError), but the second has to be filtered afterwards.
Putting the two conditions into one comprehension might not be common,
but it's a bit odd to have them mean different things.

Agreed that two ifs applied at different times is fairly odd, but as long
as _ is known to be magical, it's fairly intuitive, in my opinion.

Also, Koos's offering above:

> [abs(x) for x in numbers if > 5]

Is also very nice, but I don't like it when the filtering is:

[abs(x) for x in numbers if]

On Tue, Mar 8, 2016 at 12:52 PM, Chris Angelico <rosuav at gmail.com> wrote:

> On Wed, Mar 9, 2016 at 7:46 AM, Mark Mollineaux
> <bufordsharkley at gmail.com> wrote:
> > This map-then-filter shortcoming is one of the most common warts I
> encounter
> > with python syntax, and I would absolutely love an improvement here.
> >
> > I think ChrisA is closest with:
> >
> >> 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]
> >
> > But I wonder, why not just:
> >
> > [abs(x) for x in numbers if _ > 5]
> >
> > Where _ refers to the return expression within a comprehension, and is
> > interpreted specially in this context?
>
> That makes it somewhat magical; compare these two conditions:
>
> [(base//x) % 10 for x in numbers if x if _]
>
> The first one MUST be filtered prior to mapping (else you'll get a
> ZeroDivisionError), but the second has to be filtered afterwards.
> Putting the two conditions into one comprehension might not be common,
> but it's a bit odd to have them mean different things.
>
> ChrisA
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160308/4efe6197/attachment.html>


More information about the Python-ideas mailing list