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

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 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)
>   ...

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

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


More information about the Python-Dev mailing list