[Python-Dev] Don't set local variable in a list comprehension or generator
Terry Reedy
tjreedy at udel.edu
Thu May 19 03:44:24 CEST 2011
On 5/18/2011 5:34 PM, Victor Stinner wrote:
You initial example gave me the impression that the issue has something
to do with join in particular, or even comprehensions in particular. It
is really about for loops.
> squares = (x*x for x in range(10000))
>>> dis('for x in range(3): y = x*x')
1 0 SETUP_LOOP 30 (to 33)
3 LOAD_NAME 0 (range)
6 LOAD_CONST 0 (3)
9 CALL_FUNCTION 1
12 GET_ITER
>> 13 FOR_ITER 16 (to 32)
16 STORE_NAME 1 (x)
19 LOAD_NAME 1 (x)
22 LOAD_NAME 1 (x)
25 BINARY_MULTIPLY
26 STORE_NAME 2 (y)
29 JUMP_ABSOLUTE 13
>> 32 POP_BLOCK
>> 33 LOAD_CONST 1 (None)
36 RETURN_VALUE
> You don't really need the "x" variable, you just want the square.
It is nothing new that hand-crafted assembler (which mnemonic bytecode
is) can sometimes beat a compiler. In this case, you want store, load,
load before the multiply replaced with dup, and you cannot get that with
Python code without a much smarter optimizer.
>
--
Terry Jan Reedy
More information about the Python-Dev
mailing list