How Scope of variable (local global and nonlocal) work for mutable object like List in Python?

krishna :

I am writing program as below for testing my knowledge about Python Scope of variable

def show(a,b):
    def add():
        a = a+b #Error at this line "UnboundLocalError: local variable 'a' referenced before assignment" 
#I know we can use nonlocal a,b to avoid error 
    add()
    print("a=",a)
x=4
y=2
show(x,y)

Then I tried same program with some little changes with x and y as list. Code is as shown below

def show(a,b):
    def add():
        a[0] = a[0]+b[0] #No Error at this line
    add()
    print("a=",a[0])

x=[4]
y=[2]
show(x,y)

And this code runs fine. I am not getting this strange behavior in python.

ForceBru :

Scoping rules are the same for all variables. It doesn't matter what objects they refer to.

However, a = a + b and a[0] = a[0] + b[0] are different things.

  1. The first one is assignment to a global variable that is actually treated as local by Python. Details can be found in this post: Python function global variables?

  2. The second one is syntactic sugar and doesn't do an assignment! It's desugared (translated internally) to a call to __setitem__:

    a.__setitem__(0, a[0] + b[0])
    

    As you can see, no assignment here, point (1) above doesn't apply, so no issues here.

In general, code like a[i] = b will be translated to a.__setitem__(i, b), and some other syntax is translated into function calls as well, like a + b can be a.__add__(b), a[0] is a.__getitem__(0) and so on.

So, a[0] = a[0] + b[0] will end up being this monstrosity:

a.__setitem__(0, a.__getitem__(0).__add__(b.__getitem__(0)))

No assignment - no problem with global variables suddenly turned local.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=21314&siteId=1