Default scope of variables

Joshua Landau joshua.landau.ws at gmail.com
Thu Jul 4 00:30:03 EDT 2013


On 4 July 2013 05:07, Chris Angelico <rosuav at gmail.com> wrote:
> 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.

Coffeescript, which compiles to Javascript, "fixes" the problem Steven
brought up by automatically declaring variables so that you don't have
to. But what do you think this does?:

a = 1
func = ->
    a = 2
    b = 2

The "a" in "func" is global, the "b" is local. And Coffeescript
*doesn't let* you shadow even if you explicitly want to. There just
isn't syntax for it.

That said, I'm not too convinced. Personally, the proper way to do
what you are talking about is creating a new closure. Like:

for i in range(100):
    with new_scope():
        for i in range(100):
            func(i)
    func(i) # Using i from original loop

But it's not like Python'll ever support that.



More information about the Python-list mailing list