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

Joao S. O. Bueno jsbueno at python.org.br
Wed Mar 9 00:02:32 EST 2016


So, as for the "post filter" - one can currently just express that in Python as:

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

It may have one "internal generator" - but save for the little
performance saving, I don't see this as less readable than the proposals above.

As for the reuse of a value that might come in an expensive computation,
that is something I always missed in Python - so, a couple years ago I
put together
a small package that can do just that: duplicate a computed value in a
seamlesway, without requiring
an explicit variable assignment.

To do that, I use the mechanics of stack-based languages such as
Postscript and Forth -
as of now, one can do:
`
from stackfull import push, popclear, clear

[popclear() for x in numbers if push(expensive_calculation(x)) > 5]
`
The functions pergorm stack operation in a list that is created in a
transparent way on the
current Python execution frame local variables dictionary. Works fine
in Python, Python2 and pypy.

https://pypi.python.org/pypi/stackfull/0.9

(Yes, I've just updated it a little bit, due to this on-going discussion)
---
And no, I am not suggesting this should go into the stdlib, I am just
pointing it as a helper to people
who would like that right now.


  js
 -><-


On 8 March 2016 at 22:55, Terry Reedy <tjreedy at udel.edu> wrote:
> On 3/8/2016 9:17 AM, Allan Clark wrote:
>>
>> tl;dr What is support like for adding an 'as' clause to comprehension
>> syntax? In order to allow map-then-filter, it might look like something
>> this:
>>
>>      [y for x in numbers if abs(x) as y > 5]
>
>
> -1
>
> Comprehensions abbreviate a particular pattern of collection initialization,
> nested for and if statements, and collection augmentation innermost, with
> the only binding being the loop names. They are easily translated back to
> the original pattern, although move than one level of nesting can challenge
> comprehension in the normal meaning of the work.  I strongly feel that the
> current correspondence between conprehensions and statements should be
> maintained.
>
> --
> Terry Jan Reedy
>
>
> _______________________________________________
> 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/


More information about the Python-ideas mailing list