By value or by reference?

Alex Martelli aleaxit at yahoo.com
Mon Oct 18 18:04:58 CEST 2004


Jonathan  Ellis <jbellis at gmail.com> wrote:
   ...
> > 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.

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.

I find it simpler to explain as: the semantics of argument passing are
_exactly_ identical to that of assignment (binding) to a barename; you
can fruitfully see argument passing as local (bare) names of the called
function being assigned initial values by the caller (that's exactly
what happens, in practice).  Now if you want to coin a name for that,
such as "by object reference", "by uncopied value", or whatever, be my
guest.  Trying to reuse terminology that is more generally applied to
languages where "variables are boxes" to a language where "variables are
post-it tags" is, IMHO, more likely to confuse than to help.


Alex



More information about the Python-list mailing list