By value or by reference?

Bengt Richter bokr at oz.net
Mon Oct 18 17:39:47 EDT 2004


On Mon, 18 Oct 2004 18:04:58 +0200, aleaxit at yahoo.com (Alex Martelli) wrote:

>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.
>
>
Maybe something like this can help elucidate the mechanism(s) of passing arguments?
(I.e., as a sort of automatic tuple formation from the arg list and unpacking it
into the locals indicated by the parameter name list)?

 >>> a = 1
 >>> b = 'two'
 >>> def foo(x,y):
 ...     print 'x=%r, y=%r'%(x, y)
 ...
 >>> def bar(*args):
 ...     x, y = args
 ...     print 'x=%r, y=%r'%(x, y)
 ...
 >>> c = (a, b)
 >>> foo(a,b)
 x=1, y='two'
 >>> foo(*c)
 x=1, y='two'
 >>> bar(a,b)
 x=1, y='two'
 >>> bar(*c)
 x=1, y='two'

Regards,
Bengt Richter



More information about the Python-list mailing list