Python function call by value

What is Call by Value and Call by Reference in Python?

Python Certification Course: Master the essentials

It is a way of passing arguments to a function in which the arguments get copied to the formal parameters of a function and are stored in different memory locations. In short, Any changes made within the function are not reflected in the actual parameters of the function when called.

Call by Reference

It is a way of passing arguments to a function call in which both the actual argument and formal parameters refer to the same memory locations, and any changes made within the function are reflected in the actual parameters of the function when called.

If we consider call by value and call by reference in Python, then we must keep in mind that,

Python variables are not storage containers. Rather Python’s variables are like memory references. They refer to the memory address where the value is stored.

Hence, we should know about Mutable and Immutable Objects.

Mutable objects

An object whose internal state can be changed is called a mutable object. Examples of Mutable objects are Lists, Sets, Dictionaries, bytes and arrays. User-defined classes can be mutable or immutable, depending on whether we can change their internal state.

NoteAll operations using mutable objects may or may not change the object.

Immutable objects

An object whose internal state cannot be changed is called an immutable object. Examples of immutable objects are Numbers(int, float, bool, etc), Strings, Tuples, Frozen sets(mutable version of sets are termed as Frozen sets)

NoteAll operations using immutable objects make copies.

Code Snippet explaining mutable and immutable objects

Output and Explanation:

Now that we know what Mutable and Immutable Objects are, Lets delve into What is Call by value and Call by reference in Python.

Call by Value in Python

When Immutable objects such as whole numbers, strings, etc are passed as arguments to the function call, the it can be considered as Call by Value.

This is because when the values are modified within the function, then the changes do not get reflected outside the function.

Example showing Call by Value in Python

Explanation: As we can see here, the value of the number changed from 13 to 15 , inside the function, but the value remained 13 itself outside the function. Hence, the changes did not reflect in the value assigned outside the function.

Call by Reference in Python

When Mutable objects such as list, dict, set, etc., are passed as arguments to the function call, it can be called Call by reference in Python. When the values are modified within the function, the change also gets reflected outside the function.

Example 1 showing Call by reference in Python

Explanation: Here we can see that the list value within the function changed from [1] to [1, 3, 1] and the changes got reflected outside the function.

But, Consider this example-

Example 1 showing Call by reference in Python

Unlike previous example above, new values are assigned to myList but after function call we see that all the changes do not get reflected outside the function.

Then, is it Call by reference?

Lets take a look into the memory environment for both the examples. We’ll print the address of the list before calling the function and after calling the function.

For example 1

Explanation: Here we see the value of the list before calling the function, within the function and after calling the function gets stored in the same memory address. Hence, changes made within function gets reflected outside the function as well.

Lets consider Example 2 now:

Explanation: Here we see that, the address of the list changes when new values are assigned to it within the function but outside the function, the value still refers to the previous memory allocation.Hence, the changes made within the function do not get reflected outside the function.

What do we infer? Well, we see that when mutable objects are passed as arguments to a function then there are two cases:

a.) Change is reflected outside function This is when a mutable object is passed as argument and no new value is assigned to it, ie.,the values refer to the same memory address.

b.) Change is not reflected outside function This is when a mutable object is passed as argument and new values or datatype is assigned to it within the function, ie. when the values outside the function and the values assigned within function refer to different memory addresses.

Note:
In python the changes in values before and after function call solely depends on the memory address.There is object reference depending on memory environment.
Arguments are passed by assignment in Python. Since, assignment just creates references to objects, there’s no alias between an argument name in the caller and callee.

mutable and Immutable objects

Difference between Call by Value and Call by Reference

Call by Value Call by Reference
1. The arguments are copied to the function parameter. The arguments, as well as the formal parameters, refer to the same location.
2. Changes made inside the functions are not reflected. Changes made inside the functions are reflected.
3. Immutable Objects are passed in arguments. Mutable objects are passed in arguments

Conclusion

  • Depending upon the mutability/immutability of it’s data type, a variable behaves differently.
  • If a variable refers to an immutable type, then any change in its value will also change the memory address it refers to. Still, if a variable refers to a mutable type, any change in the value of the mutable type will not change the memory address of the variable.
  • Arguments are passed by assignment in Python. The assignment creates references to objects.
  • Hence, Immutable objects passed as arguments are referred as in Call by Value and Mutable objects, when passed as arguments are referred to as Call by Reference.

Источник

How Call by Value and Call by Reference Work in Python?

In above example the address of varible a and b using & followed by variable name , where in function defination
* followed parameter known as pointer variable which used
to storing addresses, because of this values in varible a and b is modified.

Now we have seen what is call by value and call by reference with example

But, Python programming language uses the mechanism of the call-by-object and also call by object reference.

Each object whenever it is instantiated ,it is assigned unique id and its type if defined at runtime and id(object) returns a unique identity (integer value) of that object.

to move further into the topic first we have to understand mutable object and immutable object in python.

  • Mutable Objects
    Datatypes that can be modified or if there state can be changed those objects are known as Mutable datatype
    like (list, dictionaries, set) .
  • Immutable Objects
    Datatypes that cannot be modified or if there state cannot be changed those objects are known as Immutable datatype like **(int, float, bool, string, unicode, tuple).

So when Mutable objects are passed to the function call then it is treated as **call by value.**

And When Immutable objects are passed to the function call and there value is modified then it is treated as **call by reference.**

For the sake of simplicity we’re going to use the word call by value and call by reference instead of (call by object) and (call by object reference) respectivly.

let’s take examples for call by reference and call by value

Example :- Call by reference (with Immutable objects (int, float, bool, string) and no object state modified) in python

num1 = 43 num2 = 12.44 num3 = False name = 'hello' print("Id in main function scope") print(f"id of num1 = ") print(f"id of num2 = ") print(f"id of num2 = ") print(f"id of name = ") def call_by_reference(num1,num2,num3,name): print("\nId within function") print(f"id of num1 = ") print(f"id of num2 = ") print(f"id of num2 = ") print(f"id of name = ") call_by_reference(num1,num2,num3,name) Output :- Id in main function scope id of num1 = 94157957099328 id of num2 = 140438713493200 id of num2 = 94157956423968 id of name = 140438848940272 Id within function id of num1 = 94157957099328 id of num2 = 140438713493200 id of num2 = 94157956423968 id of name = 140438848940272 

So we can see that the id’s the objects (num1, num2, num3) has not change becuase have not applied modification to those objects.

Example :- Call by reference (with Mutable objects (list ,dict) and object state modified) in python

names = ['ram', 'shyam', 'bharat'] d = print("Id in main function scope") print(f"id of names list = ") print(f"id of d dict = ") def call_by_reference(name, d): print("Id within function") d['sam'] = 12 names.append('john') print("\nModified Objects id :-") print(f"id of names list = ") print(f"id of d dict = ") call_by_reference(names, d) print("Modfied list and dict") print(f"names = ") print(f"dict = ") Output :- Id in main function scope id of names list = 140439297460096 id of d dict = 140438712179600 Id within function Modified Objects id :- id of names list = 140439297460096 id of d dict = 140438712179600 Modfied list and dict names = ['ram', 'shyam', 'bharat', 'john'] dict =

We can see even after modifying the objects state the id’s of the object remains unchanged because the objects datatype are mutable objects here by ,even if the object state is modified
it is treated as call by reference(call by object reference).

Example :- Call by Value (with Immutable objects (int, float, bool, string) and object state modified) in python

num1 = 43 num2 = 12.44 num3 = False name = 'hello' print("Id in main function scope") print(f"id of num1 = ") print(f"id of num2 = ") print(f"id of num2 = ") print(f"id of name = ") def call_by_value(num1,num2,num3,name): print("\nId within function") num1 = 1 num2 = 2 num3 = 3 name = 'sam' print("Modified Objects id") print(f"id of num1 = ") print(f"id of num2 = ") print(f"id of num2 = ") print(f"id of name = ") call_by_value(num1,num2,num3,name) print("\Unmodified int, float, bool, string objects value in global scope") print(f'num1 = ') print(f'num2 = ') print(f'num3 = ') Output :- Id in main function scope id of num1 = 94157957099328 id of num2 = 140438713494320 id of num2 = 94157956423968 id of name = 140438848940272 Id within function Modified Objects id id of num1 = 94157957097984 id of num2 = 94157957098016 id of num2 = 94157957098048 id of name = 140438713157936 Unmodified int, float, bool, string objects value in global scope num1 = 43 num2 = 12.44 num3 = False 

In the above example we can see that after modifying the Immuatable objects the object id’s were diffrent , this is because we cannot modify the value of Immutables and because of this new 3 objects named (num1, num2, num3, name) where created in the function local scope after the function call we have also print the value to verify the objects in the global scope remain unchanged.

Example :- Call by Value (with Immutable objects (tuple) and object state modified) in python

names = ('ram', 'shyam', 'bharat') print("Id in main function scope") print(f"id of names tuple = ") def call_by_value(name, d): print("Id within function") names = ('ram','shyam','bharat','john') print(f"modified object value \n") print("\nModified Objects id :-") print(f"id of names tuple = ") call_by_value(names, d) print("\nUnchanged tuple object in global scope") print(f"names = ") Output :- Id in main function scope id of names tuple = 140438712974144 Id within function modified object value ('ram', 'shyam', 'bharat', 'john') Modified Objects id :- id of names tuple = 140438712255888 Unchanged tuple object in global scope names = ('ram', 'shyam', 'bharat') 

In the above example we can have assigned a new tuple with same elements + one more element because (tuple datatype does not support any add method) andchecked the object id which is diffrent because a new object gets created and also the global object remain unchanged because of it’s Immutable nature.

With this example we have come to an end
hope you all have understood the topics
covered in this article.

Источник

Читайте также:  Цвет ссылок
Оцените статью