Sunday, August 22, 2010

Is variable scope in Python broken?

I've come across this weirdness before when trying to write functional python code.  It seems you can access the variables declared in the function above but not alter them in anyway or you'll get a UnboundLocalError.  In PHP you're allowed to alter the variable but the changes will only take place in the current scope (unless you global it first).  Python just gives you an error.

Example code:

#!/usr/bin/python

def myfunc1(var1="VAR 1"):
    var2="VAR 2"
    def myfunc2():
        print var1
        print var2
    myfunc2()
myfunc1()

def myfunc3(var1="VAR 1"):
    var2="VAR 2"
    def myfunc4():
        var1 += " WORKING!"
        var2 += " WORKING!"
    myfunc4()
myfunc3()


Expected error:

UnboundLocalError: local variable 'var1' referenced before assignment

If anybody knows why this is I'd be interested to hear why.

0 comments:

Post a Comment