Information passing in Python (Pass by object reference)

Hello, reader!
Are function calls "pass-by-value" or "pass-by-reference" in python? 
If you have ever used functions in python, this doubt would have come to your mind. This post aims to simplify the commonly used answer, "Object references are passed by value.", and explain the concept from the basics.

Pre-requisite knowledge:

    1. Everything is an object in python.

In Python, whenever an assignment statement, say, x = 2 is called, the 'identifier' (also called 'name') references an instance of int class having value 2. After that, if you call, y = x , an 'alias' is created which is also a name pointing to the same instance. 

    2. Python's built-in classes can be mutable or immutable.

Consider two classes, float and list. You might know that float is an immutable built-in class defined in python, whereas, list is mutable. What it means is that if you do:
        x = 2.0
        y = x + 1.1
at first step, a new instance of float with value 2.0 is created and name 'x' assigned to it. In the second step, an instance of float with value 1.1 is created, then it is added to the value of instance pointed by x, and the result of addition is stored in a new instance. This new instance is given the name 'y'

So, the important point to observe is that in python, we don't simply add the value to existing instance, but create a new instance to assign to a particular name/ identifier.

Information Passing:

Consider function:

1.   def addOne(y):
2.       y += 1
3.       print(y)
4.       return y
5.
6.   x = 2
7.   z = addOne(x) 
8.   print(x)
9.   print(z)

Let us trace the program execution:

Line no.   |    Action
(6)                An instance of float with value 2 is created. Name 'x' is assigned to it.
(7)                Function addOne is called.
(1)                As the formal parameter is 'y', an identifier 'y' now refers to the instance referred by 'x'.
(2)                'y' now refers to a new instance with value '3'. ( Read 2nd pre-requisite above.)
(3)                'y' points to new instance. Hence, '3' is printed.
(4)                returns instance referred by 'y'
(7)                new name 'z', now refers to instance returned. 'y' is destroyed.
(8)                'x' still points to the instance with value 2. Hence, '2' is printed.
(9)                'z' points to the instance with value 3. Hence, '3' is printed.


I hope that this simple example clarifies how information is passed in Python when a function is called. If you still have any doubts, feel free to comment below and I'll try to help you to the best of my ability.

* FIN *

Comments

Post a Comment

Popular posts from this blog

Update firefox in Ubuntu from tar.bz2

A Project Manager's guide to using branches in git