[Python-Dev] Python3 compiled listcomp can't see local var - bug or feature?

Rob Cliffe rob.cliffe at btinternet.com
Mon Jun 11 18:06:36 EDT 2018

Skip, I think you have misunderstood the  point I was making.  It was 
not whether the loop variable should leak out of a list comprehension.  
Rather, it was whether a local variable should, so to speak, "leak into" 
a list comprehension.  And the answer is: it depends on whether the code 
is executed normally, or via exec/eval.  Example:

def Test():
       x = 1
       print([x+i for i in range(1,3)])              # Prints [2,3]
       exec('print([x+i for i in range(1,3)])') # Raises NameError (x)

I (at least at first) found the difference in behaviour surprising.


Rob Cliffe

On 08/06/2018 19:27, Skip Montanaro wrote:
>> Is this a bug or a feature?
> The bug was me being so excited about the new construct (I pushed in
> someone else's work, can't recall who now, maybe Fredrik Lundh?) that
> I didn't consider that leaking the loop variable out of the list
> comprehension was a bad idea. Think of the Py3 behavior as one of
> those "corrections" to things which were "got wrong" in Python 1 or 2.
> :-)
> Skip
> ---
> This email has been checked for viruses by AVG.
> http://www.avg.com

More information about the Python-Dev mailing list