Incorrect scope of list comprehension variables

Alain Ketterlin alain at dpt-info.u-strasbg.fr
Sat Apr 17 11:23:45 EDT 2010


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:

> On Sat, 17 Apr 2010 12:05:03 +0200, Alain Ketterlin wrote:
>
>>> I don't know of any language that creates a new scope for loop
>>> variables, but perhaps that's just my ignorance...
>> 
>> I think Pascal and Modula-2 do this, Fortran does this, as well as Ada.
>
> Pascal doesn't do this.
[...]
>   for i := 1 to 3 do
>     begin
>       writeln(i);
>     end;
>   writeln(i);
[...]

At http://standardpascal.org/iso7185.html#6.8.3.9%20For-statements
(sorry, I didn't find a more readable version), I read (second
paragraph, fourth sentence) :

"After a for-statement is executed, other than being left by a
goto-statement, the control-variable shall be undefined."

So, at least, the compiler should emit a warning.

> However you can't assign to the loop variable inside the loop. Outside of 
> the loop, it is treated as just an ordinary variable and you can assign 
> to it as usual.

I read the excerpt above as: you have to re-assign to it before using it.

The corner-case is obvious: if the loop body is not executed at all,
you cannot assume the "control-variable" will have the first value. I'm
curious to know what gets printed if you swap 1 and 3 in the above code.

-- Alain.



More information about the Python-list mailing list