Bzhenko Bzhenko - 25 days ago 6
Python Question

How to make a "local object" in Python?

I wonder why Python behaves differently in the cases below?

Case 1. I change local integer variable but global variable remains the same. Well, that's OK.

N = 1

def Func1(x):
x = 0

Func1(N)
print(N) # prints 1


Case 2. I change property of local object... and it seems that I've changed global object.

class C1:
def __init__(self):
self.A = 1

Obj1 = C1()

def Func2(x):
x.A = 0 #here is a confusing moment

Func2(Obj1)
print(Obj1.A) #prints 0


Maybe I have incomplete understanding about can object actually be local or not? In that case how can I code something similar to "local object"?

Answer

In python, arguments to functions are passed by assignment. [1] And in python, objects are not copied on assignment. So in your second example, to make what you call a local copy of the object, you will have to copy it explicitly, for instance using copy.deepcopy(x) [2]

So your second code would become:

import copy
class C1:
    def __init__(self):
        self.A = 1

Obj1 = C1()

def Func2(x):
    x = copy.deepcopy(x) # Make a local copy of the object
    x.A = 0  #No more confusion

Func2(Obj1)
print(Obj1.A) #prints 1

[1] https://docs.python.org/3.4/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference

[2] https://docs.python.org/3/library/copy.html