Python Newbie

Vito De Tullio vito.detullio at gmail.com
Sun Feb 24 03:23:41 EST 2013


piterrr.dolinski at gmail.com wrote:

> You see, Javascript, for one, behaves the same way as Python (no variable
> declaration) but JS has curly braces and you know the variable you have
> just used is limited in scope to the code within the { }. With Python, you
> have to search the whole file.

I don't know if you know javascript, but I think your experience with it is 
limited, as you listed two of of the many common pitfalls of javascript:

javascript has optional variable declaration, but if you don't declare a 
variable (such as a local variable in a function) it binds itself in the 
global scope;

in c/c++/c#/java... curly braces define a new scope, in javascript no.

if you do in javascript

    function foo() {
        if (some condition) {
           a = 'something';
        }

        alert(a);
    }

the moment you call the foo() function (and some condition is true), a 
global variable "a" is created. (this time you *really* need to search not 
the whole .js file, but the whole project, as there is no "file-level" 
globals in javascript)

if you instead use the 'var' keyword to define explicitly a local variable

    function foo() {
        if (some condition) {
           var a = 'something';
        }

        alert(a);
    }

while you don't create a global variable, the "a" variable is still 
accessible outside the "if" braces.

this is the reason most javascript linters (most notably jslint) force the 
first statement of every function to be the definition of all function 
variables.



by this point of view, python and javascript have the same philosophy, but 
at least python doesn't allow implicit global variable definition


-- 
ZeD





More information about the Python-list mailing list