Incorrect scope of list comprehension variables

Dave Angel davea at ieee.org
Sat Apr 17 11:15:22 CEST 2010


Steven D'Aprano wrote:
> On Fri, 16 Apr 2010 08:48:03 -0700, Aahz wrote:
>
>   
>> In article <4bb92850$0$8827$c3e8da3 at news.astraweb.com>, Steven D'Aprano 
>> <steve at REMOVE-THIS-cybersource.com.au> wrote:
>>     
>>> Nevertheless, it is a common intuition that the list comp variable
>>> should *not* be exposed outside of the list comp, and that the for-loop
>>> variable should. Perhaps it makes no sense, but it is very common --
>>> I've never heard of anyone being surprised that the for-loop variable is
>>> exposed, but I've seen many people surprised by the fact that list-comps
>>> do expose their loop variable.
>>>       
>> I've definitely seen people surprised by the for-loop behavior.
>>     
>
> What programming languages were they used to (if any)?
>
> I don't know of any language that creates a new scope for loop variables, 
> but perhaps that's just my ignorance...
>
>
>   
It's not clear whether a language like C or C++ has "loop variables."  
It just has variables with varying scope depending on where they're 
declared.  And you can add extra braces with the sole purpose being to 
introduce new variable scoping.

But two things that changed as C evolved were where you could introduce 
new variables, and the lifetime of variables introduced in the loop 
control structure, rather than inside the braces.  The first change was 
in C++ from the start, but I think the second change was also an 
evolution in C++.

1)  In original C, all declarations in a given scope had to occur before 
any executable code began.  For example, the following was illegal:
     int a=12, b=42;
     myfunc(a, b);
     int c = 9;       /* illegal */

2) In original C, and I think in C++, the lifetime of i lasted long 
after the loop ended.
     for (int i=0; i< limit; ++i)
     {
           z += i;
     }
      i is still valid after this curly brace

In C99, and at least in later C++, the scope of i ends with the curly, 
as though there were another invisible pair of braces:
     {
     for (int i=0; i< limit; ++i)
     {
           z += i;
     }}
      i is no longer valid here

Because C and C++ have explicit declarations, people who need the loop 
variable after the loop is done can simply declare the loop variable 
before the for statement.

DaveA




More information about the Python-list mailing list