Pass by reference ?

Justin Sheehy dworkin at ccs.neu.edu
Wed Apr 5 21:53:47 EDT 2000


"Robert W. Cunningham" <rcunning at acm.org> writes:

[snip long explanation of dubious relevance to the following code]

> Let's pick some representations:
> 
>    a=5
>    b=(5)
>    c=[5]
>    d={"five":5}
> 
> And let's create some functions to manipulate them.  In this case I 
> chose an extremely generic Python function, though I SHOULD choose a 
> separate function for each representation to illustrate that the 
> function doesn't matter:  The passing does.
> 
>    def Nuke(w):
>      print w,
>      w=None
>      print w
> 
> Let's call each of these functions:
> 
>    Nuke(a)
>    Nuke(b)
>    Nuke(c)
>    Nuke(d)
> 
> Look at the output:
> 
>    5 None
>    5 None
>    [5] None
>    {"five":5} None
> 
> And then look at the original values:
> 
>    print a,b,c,d
> 
>    5 5 [5] {"five":5}
> 
> None changed!  Therefore, representations the functions modified were 
> DIFFERENT from those passed, though it is clear that the correct VALUE 
> was passed.

No, unless by VALUE you mean the value of the reference that was passed.

Your assertion here is not really related to "pass by reference"
vs "pass by value".  All that your example does is demonstrate the
semantics of assignment in Python.  The two are certainly related
topics, but you have not shown anything interesting about argument
passing here.

The line:

  w=None  

simply makes the local variable `w' no longer be bound to the argument 
passed, but rather to None.  Reassigning the name `w' is simply that:
reassigning a name.  Whatever was previously referred to by that name
is irrelevant.

To show that Python does not do what you claim, I offer the following
slight change to your example:

>>> def NukeToo(w):
...   print w,
...   w[1] = None
...   print w
... 
>>> a = [1, 2, 3]
>>> NukeToo(a)
[1, 2, 3] [1, None, 3]
>>> a
[1, None, 3]

Does that still meet your old definition of pass-by-value?

-Justin

 




More information about the Python-list mailing list