By value or by reference?

Gustavo Niemeyer niemeyer at conectiva.com
Wed Oct 20 14:23:30 EDT 2004


> > > By reference to an object....See the python tutorial.
> > 
> > Wrong.  Here is the difference between pass by reference and pass by
> > value to CS types:
> > 
> > >>> def foo(a): a = 1
> > ...
> > >>> i = 10
> > >>> foo(i)
> > >>> print i
> > 
> > With pass-by-reference, i would now be 1.  However, since python is
> > pass-by-value, it remains 10.
> 
> ...so you tell "CS types" it's pass-by-value, and they come right back
> with
> 
> def bar(b): b.append(2)
> 
> z = []
> bar(z)
> print z
> 
> With pass-by-value, they'll say, z would still be [].  However, since
> what is passed is not just (a copy of) the value, but (a reference to)
> the object itself, z is [2] instead.

It really depends on what you claim to be passed by value. In Python,
objects are passed by reference, but references are passed by value. So
one may say that z is being passed by value, since what is passed is a
copy of the reference. With that in mind, one may correctly say that
Python always do pass-by-value, and correctly say that it always do
pass-by-reference.

Here is an article presenting the issue in more detail (much more :-):

http://www-106.ibm.com/developerworks/java/library/j-passbyval/

> The terminology problem may be due to the fact that, in python, the
> value of a name is a reference to an object.  So, you always pass the
> value (no implicity copying), and that value is always a reference.
[...]

That's it.

-- 
Gustavo Niemeyer
http://niemeyer.net



More information about the Python-list mailing list