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

Steven D'Aprano steve at pearwood.info
Sat Jun 20 11:09:40 CEST 2009


On Sat, 20 Jun 2009 09:45:58 am Lie Ryan wrote:
> How about this syntax which would solve your concern for the semantic
> change:
>
> [x**x as F for x in lst if F() < 100]

Let's look at what that would be equivalent to.

L = []
for x in lst:
    F = lambda x=x: x**x  # Need to use default value in the 
    # lambda otherwise all elements will have the same value.
    tmp = F()
    if tmp < 100:
        L.append(tmp)


It's not clear why you think this is an improvement over:

[x**x as F for x in lst if F < 100]  # note the missing ()s

which would be equivalent to:

L = []
for x in lst:
    F = x**x
    if F < 100:
        L.append(F)




Despite what you say here:

> The advantage of F being callable is that it does not need semantic
> change, the filtering part will be done before expression just like
> it is right now.

That's not true. It can't be true. If you want to filter on x**x being 
greater than 100, you need to calculate x**x first. In theory, a 
sufficiently clever compiler could recognise that, say, x**x < 100 
implies 0 <= x < 3.59728 (approx), but in general, you can't predict 
the value of f(x) without actually calculating f(x).

What happens if you accidentally forget to put brackets after the F 
expression? Do you get a syntax error? Undefined behaviour? A runtime 
exception?



-- 
Steven D'Aprano



More information about the Python-ideas mailing list