Default scope of variables

Chris Angelico rosuav at gmail.com
Thu Jul 4 00:07:55 EDT 2013


On Thu, Jul 4, 2013 at 1:27 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> With respect to the Huffman coding of declarations, Javascript gets it
> backwards. Locals ought to be more common, but they require more typing.
> Locals are safer, better, more desirable than globals, and so it should
> be easier to use locals than globals, not the other way around. Having to
> declare "give me the safe kind of variable", while getting the harmful[1]
> kind of variable for free, strikes me as arse-backwards. Lazy, naive or
> careless coders get globals[2] by default or accident. That's bad.

I agree that Javascript has it wrong, but not quite for the reason you
say. The advantage of declaring locals is a flexibility: you can have
multiple unique variables with the same name in the same function.
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
}

Also, C++ overlays the "this is local" declaration with the "this
contains this type" declaration, which neither Python nor Javascript
bothers with; that makes the declaration feel less redundant.

Granted, this flexibility is mostly of value when writing huge
functions with complex nesting, but it is something that I find
convenient.

In terms of Huffman coding, every C++ variable must be declared,
somewhere. It's not a matter of declaring globals or declaring locals
- you just declare variables. If you declare them at file scope,
they're globals; if at function scope, they're locals. There's really
no difference. Everything's visible at its own level and those further
in, and not those further out.

I do see the convenience of the Python system, and I do like it; but
someone needs to speak up for the foolish and pathetic :)

ChrisA



More information about the Python-list mailing list