Alex Rivera | Logout

Difference between closures in python and javascript

Asked 2011-05-06T10:37:00.693
9

In JS, we can write closure like:

function f(){
var a=0;
function g(){
    alert(a++);
}
return g;
}
g=f()
g()

However, if I write following code in python

def f():
    a=0
    def g():
        a+=1
        print a
    return g
g=f()
g()

Then I get UnboundedLocalError.

Can anyone tell me the difference between closure in python and JS?

Edit
Report

1 Answer

12

When you use a += 1 in Python it refers to a local (uninitialized) variable in scope of g function. Basically you can read variables from upper scopes, but if you try to write it will refer to a variable in most recent scope. To make it work like you want you have to use nonlocal keyword that is only present Python 3. In Python 2 you can't do that as far as I know, unless the variable you're trying to change is is global, then global keyword comes to the rescue.

def f():
    a=0
    def g():
        nonlocal a
        a+=1
        print a
    return g
g=f()
g()
answered 2011-05-06T10:56:48.397

Your Answer