function arguments passed by reference

Josef Meile jmeile at hotmail.com
Thu Mar 4 15:13:28 CET 2004


Marcello Pietrobon wrote:
> John Roth wrote:
> 
>> "Marcello Pietrobon" <teiffel at attglobal.net> wrote in message
>> news:mailman.8.1078344338.736.python-list at python.org...
>>  
>>
>>> Hello,
>>>
>>> My background is C++
>>>
>>> I would like to know for sure if it is possible to pass a value by
>>> reference to a function AND having it changed by the function itself
>>>
>>>
>>> def changeValue( text ):
>>>    text = 'c'
>>>    print text
>>>    return
>>>
>>> >>> txt = 'a'
>>> >>>changeValue( txt )
>>> 'c'
>>> >>>print txt
>>> 'a'
>>>
>>> Question 1)
>>> I guess that in Python ( differently than in C++)  somehow txt is passed
>>> by reference even if its value is not changed.
>>> Is this true ?
>>>
>>> Question 2)
>>> How can I define a function that changes the value of txt ( without
>>> having to return the changed value ) ?
>>>
>>> Question 3)
>>> Is there some documentation talking extensively about this ?
>>>   
>>
>>
>> The key concept is that everything is an object, and all objects
>> are passed by reference in the sense that what's bound to the
>> funtion's parameters is the objects that were passed in.
>>
>> However, you cannot affect the bindings in the calling environment.
>> Regardless of what you do (unless you do some deep magic with
>> the invocation stack) nothing is going to affect the bindings in the
>> caller.
>>
>> So you can rebind anything you want to the parameters within
>> the function, and it will have no effect on the calling environment.
>>
>> On the other hand, if you mutate a mutable object that was passed
>> as a parameter, that change will be visible after you return.
>>
>> For  example:
>>
>> def foo(bar):
>>    bar = "shazoom"
>>
>> a = "shazam"
>> foo(a)
>>
>> The result is that a is still "shazam."
>>
>> However, if you do this:
>>
>> def foo(bar):
>>    bar.append("shazoom")
>>
>> a = ["shazam"]
>> foo(a)
>>
>> the result is:
>>
>> ["shazam", "shazoom"]
>>
>> HTH
>> John Roth
>>
>> "shazoom" ::= ["strength", "health", "aptitude", "zeal", "ox, power of",
>> "ox, power of another", "money"]
>>
>> whatever the value you passed in remains.
>>  
>>
> 
> Thank you for the answers,
> 
> difficult to get used to these concepts after coming from C++ !
> But I am starting to understand:
> the main difference between Python and C++ is that I need to keep in 
> mind what is mutable and what is not mutable in Python
You could also return tupples like

 >>> def foo(a,b):
...   a+=2
...   b+=3
...   return a,b
...
 >>> a=1
 >>> b=2
 >>> a,b=foo(a,b)

 >>> a
3
 >>> b
5

Regards,
Josef




More information about the Python-list mailing list