function arguments passed by reference

John Roth newsgroups at jhrothjr.com
Wed Mar 3 16:23:20 EST 2004


"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,
> Marcello
>
>
>





More information about the Python-list mailing list