"always passes by reference"

Huaiyu Zhu hzhu at localhost.localdomain
Mon Jul 31 03:56:10 EDT 2000


On 30 Jul 2000 22:11:50 GMT, (Greg Weeks) <weeks at golden.dtc.hp.com> wrote:
>Martijn Faassen (m.faassen at vet.uu.nl) wrote:
>: Perhaps there is some other semantics for 'value' and 'reference' stemming
>: from another programming tradition that I'm not aware about, though.
>
>There is, but it may wither away as time goes on.  I guess I'm trying to
>keep it alive.  Consider the following snippet of Python code:
>
>    def f(x):
>	x = <something>
>
>    a = <something_else>
>    f(a)
>    
>At this point in the program, a is still <something_else>.
>
>On the other hand, in the analogous Perl code, things are different.
>
>    sub f {
>	$_[0] = <something>;
>    }
>
>    $a = <something_else>;
>    f($a);
>
>At this point, $a is <something>.  The function f did not just receive the
>pattern of bits that were written into $a.  f received the *address* of the
>variable $a, dereferenced it, and called the result $_[0].  So assigning to
>$_[0] is the same as assigning to $a.
>

The difference in the above example is not in passing by reference or value
(both pass by reference) but in whether assignments can change values (like
Perl) or just reference (like Python).  In the following, both x got a
reference to a.  That is, they point to the same object.  The difference
comes only when the assingment changes the reference in Python but the
underlying data in Perl (through one more step of dereference):

[Python]
a = something
x = a
x = somethingelse
print a # it's still something

[Perl]
$a = something;
$x = \$a;
$$x = somethingelse;
print $a;  # it's now somethingelse

Had this not been an assignment to x, but a method call, they would have the
same effects, because a and x would still be pointing to the same object:

[Python]
x.modify()  # a is modified as well 

[Perl]
$x->modify();  # $a is modified as well

The best way of "thinking in perl about python" :-) is perhaps 

$a = \something       # this is first assingment
$x = $a               # this is the variable passing
$x = \somethingelse   # this is the assingment in function f

Now $$x becomes somethingelse but $$a remains unchanged.  Clearly in Python
"every name is a reference" in the Perl sense.

Huaiyu



More information about the Python-list mailing list