[Python-ideas] Accessing the result of comprehension's expression from the conditional

Mathias Panzenböck grosser.meister.morti at gmx.net
Sat Jun 20 21:29:27 CEST 2009

average wrote:
> From: 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.
>> I'm suggesting about something like:
>> [f(x) for x in l if @ > 0]
>> where @ is the result of the listcomp's expression (i.e. f(x))
>> Personally, I don't like the use of symbols like @, as python is not
>> perl. I'm still thinking of a better syntax/approach and is open for
>> suggestion.
>> What do you guys think?
> I think it's a fine idea.  The English language has evolved such a
> construct, typically used when one wants to highlight (rather than
> simply *refer* (as a pronoun does) to) the dominant noun without
> resorting to redundancy.
> [f(x) for x in l if same > 0]  OR another possibility
> [f(x) for x in l if self > 0]
> obviously syntax highlighting makes this (or any keyword) standout
> better.  Would be interesting to consider other usages for such a
> keyword addition (in the case of the former).

I dunno. What about nested constructs? Such unnamed variables lead to 
ambiguities. E.g.:

[f(x) for x in l1 if y > sum(z for f in l2 if @ > 0)]

To which value does the @ refer to? To the most inner one would be an obvious 
solution. But then, how do you refer to the outer value? It suddenly gets 
invisible (overwritten?). Use @@ for the next outer value? No I don't like it.


More information about the Python-ideas mailing list