Closure comparison in Python and Javascript

  • 2020-04-02 14:33:34
  • OfStack

As script language, the python and Javascript have similar variable scope, not like PHP, all the variables and functions of the internal external is cut off, that is to say, the function to deal with the external data, you must use the parameter passed in the need to deal with data (using global keywords don't discuss here), and python and Javascript is different, if a declared variable in function, it will find on the net, step by step until the return a value or undefined.

So, python's closures should be pretty simple, and like javascript, we write code like this:


def func1():
    a = 1
    def func2():
        a = a + 1
        return a
    return func2
re=func1()
print re()
print re()


However, the reality is that instead of printing out 2 and 3 as we expected, the result is an error like "UnboundLocalError: local variable 'a' referenced before assignment" (referenced before assignment of local variable a). Why does this happen? Let's first look at how js implements this closure:


<script>
 function func1(){
 var a=1;
  function func2(){
  a=a+1;
  return a;
  }
 return func2;
 }
re=func1();
console.log(re());
console.log(re());
</script>

The above code runs as expected, typing 2 and 3. Notice line 5 of this program, if I put a var in front of it, what does this program look like? The end result was two "nans", and the description of var was found on the firefox developer platform:

Declares a variable, and optionally the initializing it to a value.
The scope of a variable declared with The var is The enclosing function or, for The variables declared outside a function, The global scope, which is bound to The global object).

This means that var is used to declare local variables. In the above example, if var a=a+1, then a is already a local variable in func2 and will not inherit from func1, so the result of NaN will appear in the end.

Let's go back to this closure in python, and this error is also saying that a is a local variable, and in fact, python says that all variables on the left of the assignment statement are local variables, and this a is on the left of the equal sign, so it becomes a local variable, so I can't access a in func1. How to solve this problem? If you are above python3.0, nonloacal a can be used to specify that a is not a local variable until a=a+1. The following version 3.0 does not support the nonloacal keyword, we can do this:


def func1():
    a = [1]
    def func2():
        a[0] = a[0] + 1
        return a[0]
    return func2
re=func1()
print re()
print re()

The result, as expected, prints out 2 and 3. From the examples of python and Javascript closures, learn about the similarities and differences in the scope of python and js variable declarations.


Related articles: