[Python-ideas] Accessing the result of comprehension's expression from the conditional
lie.1296 at gmail.com
Sat Jun 20 00:31:26 CEST 2009
Steven D'Aprano wrote:
> On Fri, 19 Jun 2009 05:39:32 pm Lie Ryan wrote:
>> Aahz wrote:
>>> On Fri, Jun 19, 2009, Lie Ryan wrote:
>>>> In list/generator comprehension, currently we have no way to
>>>> access the result of the expression and have to write something
>>>> like this:
>>>> [f(x) for x in l if f(x) > 0]
>>>> if f() is heavy or non-pure (i.e. have side effects), calling f()
>>>> twice might be undesirable.
>>> Listcomps and genexps are like lambdas: run up against their limits
>>> and you should switch to a regular for loop or generator.
>> I think of it not as limitation but as an odd gap in functionality. I
>> think having the semantics that the filtering is done after the
>> expression part would be much more useful than the current behavior
>> (filtering before expression).
> The point of the filtering is to avoid needlessly calculating a
> potentially expensive expression only to throw it away.
> If you want expression first, then filter, you can get that already in a
> filter(lambda x: x > 0, [f(x) for x in seq])
> Don't create new syntax when there are perfectly good functions that do
> the job already.
That's ugly because of the same reason for using map():
[y for y in map(lambda x: f(x), seq) if y > 0]
or nested comprehension:
[y for y in (f(x) for x in seq) if y > 0]
More information about the Python-ideas