"always passes by reference"

Martijn Faassen m.faassen at vet.uu.nl
Mon Jul 31 03:56:40 EDT 2000


(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.

[snip]

> 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.

Hm, I didn't work Perl worked like that without explicit dereferencing,
but what do I know about Perl. :) I *do* know that Python's behavior is
almost exactly the same; what is passed in Python is also the address of
object a. But since Python uses addresses all the time, there is no way to
change what a points expect explicit assignment, as long as it points to
an immutable.

The difference seems to be that $a in Perl is in fact *not* a reference
but a name for a value directly.

So perhaps this is a more subtle and more clear distinction:

In Perl, variables are (by default) names for values. But when you pass
a variable to a function, the *reference* of this value will be passed,
and you can change the *value* to something else. (do I get Perl's semantics
right this time?)

In Python, variables are names for references. When you pass a reference
to a function the only thing that can be changed in the function is the
state of the object through that reference; there's no way to change the
nature of that object itself (the value).

So I'd still say in Python you're passing references around. In Perl the
situation is now trickier; what is passed to functions are references to
values, but what you manipulate (by default) is the value, not the 
reference. Assignment in Perl is not name-rebinding; it's value manipulation.

Regards,

Martijn
-- 
History of the 20th Century: WW1, WW2, WW3?
No, WWW -- Could we be going in the right direction?



More information about the Python-list mailing list