[Python-Dev] Don't set local variable in a list comprehension or generator (original) (raw)

Victor Stinner victor.stinner at haypocalc.com
Thu May 19 12:39:57 CEST 2011


Le mercredi 18 mai 2011 à 21:44 -0400, Terry Reedy a écrit :

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. >>> dis('for x in range(3): y = x*x') ... >> 13 FORITER 16 (to 32) 16 STORENAME 1 (x) 19 LOADNAME 1 (x) 22 LOADNAME 1 (x) 25 BINARYMULTIPLY 26 STORENAME 2 (y) ...

Yeah, "STORE_NAME; LOAD_NAME; LOAD_NAME" can be replaced by a single opcode: DUP_TOP. But the user expects x to be defined outside the loop:

for x in range(3): y = x*x ... x 2

Well, it is possible to detect if x is used or not after the loop, but it is a little more complex to optimize than list comprehension/generator :-)

.. you cannot get that with Python code without a much smarter optimizer.

Yes, I would like to write a smarter optimizer. But I first asked if it would accepted to avoid the temporary loop variable because it changes the Python language: the user can expect a loop variable using introspection or a debugger. That's why I suggested to only enable the optimization if Python is running in optimized mode (python -O or python -OO).

Victor



More information about the Python-Dev mailing list