Default scope of variables

Ian Kelly ian.g.kelly at
Thu Jul 4 09:12:23 CEST 2013

On Wed, Jul 3, 2013 at 11:32 PM, Steven D'Aprano
<steve+comp.lang.python at> wrote:
>> Python lets you do that across but not within functions.
>> But Javascript/ECMAScript/whatever doesn't give you that. A var
>> declaration makes it function-local, no matter where the declaration is.
>> That's pointless. C++, on the other hand, lets you do this:
>> void somefunc() {
>>     for (int i=0;i<10;++i) {
>>         // do something with outer i
>>         for (int i=0;i<4;++i) {
>>             // do something with inner i
>>         }
>>         // outer i is visible again
>>     }
>>     // neither i is visible
>> }
> That's truly horrible. If the cost of this "flexibility" is that I'll
> have to read, and debug, other people's code with this sort of thing, I'm
> happy to be less flexible. For what possible reason other than "because I
> can" would you want to use the same loop variable name in two nested
> loops?

It's interesting to note that while Java and C# also allow reuse of
local variable names, they do not allow local variables declared in
inner scopes to shadow variables declared in enclosing scopes, as in
the example above.  But the following would be perfectly legal:

void somefunc() {
    for (int i = 0; i < a.size; ++i) {
        // do something with a[i]
    for (int i = 0; i < b.size; ++i) {
        // do something with b[i]

And the two i's are treated as completely separate variables here, as
arguably they should be since they're used for two distinct purposes.

More information about the Python-list mailing list