Innovation

Python Is Neither Call by Value Nor Call by Reference

It’s call-by-sharing.

In Python, the concept of “call by value” or “call by reference” doesn’t exactly apply as it does in languages like C or C++.

This is the root of much, if not all, confusion.

For example, in the following code snippet, a function receives a variable and changes its value:def test_func(val):
val = val + ‘ 2024’
print(val)

author = ‘Yang Zhou’
test_func(author)
# Yang Zhou 2024
print(author)
# Yang Zhou

As we know, call-by-reference means a function receives references to the variables passed as arguments, so modifying the arguments changes the original variables as well.

Based on the above result, the original value of the author wasn’t changed even if the test_func() changed the received variable.

Therefore, it seems Python is call-by-value, which means a copy of the object is passed to the function.

However, the following result will be surprising if it’s really called by value:def test_func(val):
print(id(val))

author = ‘Yang Zhou’
print(id(author))
# 4336030448
test_func(author)
# 4336030448

The received variable has exactly the same id as the original variable!

We know that the built-in id() function provides the memory address at which an object is stored. If val has the same id as author, it’s unreasonable to say that val is a copy of author. Obviously, it’s just another reference to the same value.

So how can we explain the results now?

Let’s go back to the fundamentals of Python:

Everything in Python is an object and the assignment operation is just binding a name to an object.

So in our example, the val is just another name besides author which is bound to the string “Yang Zhou”.

The two names have the same addresses in memory since they are bound to the same object.

However, if we change the string inside the function, because strings are immutable in Python, instead of changing the original string, a new string object.

LEAVE A RESPONSE

Your email address will not be published. Required fields are marked *