[Python-ideas] Map-then-filter in comprehensions
Paul Moore
p.f.moore at gmail.com
Tue Mar 8 11:02:45 EST 2016
On 8 March 2016 at 14:17, Allan Clark <allan.clark at gmail.com> 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]
>
> I wish to propose an extension to Python comprehension syntax in an attempt
> to make it applicable in more areas.
I understand your motivation here, but Python isn't really a
functional programming language and isn't intended to be. So
comprehensions, while powerful, are only appropriate for relatively
simple cases - at the point where they are no longer sufficiently
powerful, it's generally better to use an explicit for loop or
generator function. (In actual fact, I'm finding more and more these
days that I only use comprehensions for very simple cases, and switch
to explicit loops quite early).
So what seems to me to be missing from your proposal is an explanation
of how extending the comprehension syntax is an improvement over not
using a comprehension at all. You suggest
[y for x in numbers if abs(x) as y > 5]
as a simpler alternative to
[y for y in (abs(x) for x in numbers) if y > 5]
but I'd be much more likely to write
results = []
for x in numbers:
y = abs(x)
if y > 5:
results.append(y)
or
def bounded(it, lower):
for val in it:
absval = abs(val)
if absval > lower:
yield absval
list(bounded(numbers, 5))
Obviously real world examples would be better than artificial ones, as
artificially simple examples make terse notation look better... And in
the example using a generator, you'd be able to give it a far more
meaningful name with a bit of real-life domain terminology.
Paul
More information about the Python-ideas
mailing list