Mohd Shahril
Mohd Shahril

Reputation: 2337

Python - copy.deepcopy() doesn't work on copying local scope into global scope variable

Below is a portion of code from my latest project.

import copy

chg = None

def change(obj):
    print("obj =", obj)
    chg = copy.deepcopy(obj)
    #chg = obj
    print("chg = obj =", chg)

class B():

    def __init__(self):
        setattr(self, 'example_member', "CHANGED!")
        self.configure()

    def configure(self):
        global chg
        change(self.example_member)
        print("chg on inside =", chg)

b = B()
print("print chg on global =", chg)

So the thing is, I was expecting global chg to changes it values from None to obj's value.

So I was expecting below output :

obj = CHANGED!
chg = obj = CHANGED!
chg on inside = CHANGED!
print chg on global = CHANGED!

However, it came to my surprise that global chg identifier doesn't change at all. Below is the output produces by above code.

obj = CHANGED!
chg = obj = CHANGED!
chg on inside = None
print chg on global = None

So what I need to do in order to do the global chg with local scoped obj/example_member object value? I'm new to Python so some explanation might as do good to me. :)

Upvotes: 0

Views: 1447

Answers (1)

cdarke
cdarke

Reputation: 44364

You should declare chg as global in the change() function, otherwise it is local. An assignment inside a function to a name not declared as global within the function defaults the new variable to local scope.

def change(obj):
    global chi                       # <<<<< new line
    print("obj =", obj)
    chg = copy.deepcopy(obj)
    #chg = obj
    print("chg = obj =", chg)

Gives:

obj = CHANGED!
chg = obj = CHANGED!
chg on inside = CHANGED!
print chg on global = CHANGED!

However it would be better to avoid using a global like this.

Upvotes: 2

Related Questions