[Tutor] Pass by reference

D-Man dsh8290@rit.edu
Wed, 11 Jul 2001 12:57:56 -0400


On Wed, Jul 11, 2001 at 07:44:24PM +0530, Praveen Pathiyil wrote:
| Hi,
| 
| Can we do a "pass by reference" in python ?

Sort of -- Python always does call-by-value, but the value is always a
reference to an object on the heap.  If you assign to the argument,
then, no that won't be seen by the caller (just like C, C++ and Java).
If, instead, the reference refers to a mutable object and you modify
that object then you have the same effect (this is like using pointers
in C/C++ or a reference to a mutable object in Java).

Don't get bogged down in the implementation details and terminology
though (there can be huge flamewars as to what "pass-by-value" and
"pass-by-reference" really mean).

| Ex:
| 
| ( I would like to know whether there is a way to have the modified
| ex_dict to be visible in modified form in func1 with out explicitly
| returning that )
| 
| def func2(x, ex_dict):
|     ex_dict[x] = x*x
| 
| def func1(a):
|     ex_dict = {}
|     func2(a, ex_dict)
| 
| func1(2)

Lets try it :

>>> def func( x , ex_dict ) : ex_dict[x] = x*x
...
>>> ex_dict = {}
>>> func( 2 , ex_dict )
>>> print ex_dict
{2: 4}
>>>

It works for dictionaries because you didn't modify the reference but
instead modified the referred-to object on the heap.

If you try and do it with, say, integers it won't work because you
can't modify the integer object on the heap :

>>> def badfunc( i ) :
...     i = i * i
...     print "in badfunc, i = %d" % i
...
>>> a = 5
>>> badfunc( a )
in badfunc, i = 25
>>> print a
5
>>>

-D