0

I'm a beginner for Python. I want to know some cases to pass by values instead of references. Assume we have the class:

class myC():
    def __init__(self, x):
        self.val = x

and the functions:

def myF1(myc):
    myc.val = 1
def myF2(myDict):
    myDict['a'] = 0

if we define the variable and call the function:

a = myC(0)
myDict = {}
myF1(a)
myF2(myDict)

The value of the variable a and myDict will change since both user defined class and dictionary are mutable types. Is there ant method that just pass the value of the variable so that the variable itself won't change? If there are multiple ways, please let me know all of them. Thank you very much.

Ben Wu
  • 21
  • 1
  • 2

1 Answers1

2

Python always passes by value. However the values are references. The only value type you have in python is "reference". Variables are names and values are references.

Here is proof that python is passing by value:

def myfn(x):
    x = 2

a = {}
myfn(a)

If python passed a reference to the function, the function code would modify a by making it refer to the integer object 2, but that doesn't happen. Python only passes the value (which is a reference) to the function, and now x inside the function is storing that reference.

x is a new reference to the same object, but making x store a reference to something else won't modify a. There is no way to modify what reference the a name is holding. You can modify the dict object, but you can't change the value of a (which is a reference to the dict)

If you want a new object, you have to explictly copy it. Some immutable objects like integers have implicit copying because they return a new object on operations:

a = 5
a = a + 2

In this example a + 2 semantically creates and returns a new int object, which the name a now stores a reference to. 5 and 2 are not modified (they are immutable)

nosklo
  • 217,122
  • 57
  • 293
  • 297