Reference or Value?

Steve Holden steve at holdenweb.com
Mon Feb 23 18:45:57 CET 2009


Denis Kasak wrote:
> On Mon, Feb 23, 2009 at 5:09 AM, Steven D'Aprano
> <steven at remove.this.cybersource.com.au> wrote:
>> On Sun, 22 Feb 2009 13:37:27 -0300, andrew cooke wrote:
>>
>>> as far as i understand things, the best model is:
>>>
>>> 1 - everything is an object
>>> 2 - everything is passed by reference
>> Except that is wrong. If it were true, you could do this:
>>
>> def swap(x, y):
>>    y, x = x, y
>>
>> a = 1
>> b = 2
>> swap(a, b)
>> assert a == 2 and b == 1
>>
>>
>> but you can't, it does not work. Ergo, parameter passing in Python does
>> not have the same semantics as languages that use pass-by-reference, such
>> as Pascal and Basic. That means that even if you can justify the claim
>> "Python is pass-by-reference" by some technical argument (and I don't
>> believe you can), it is misleading to make that claim without further
>> qualifications.
> 
> You could, however, argue that the swap function doesn't work as
> expected (e.g. from a Pascal or a C++ POV) simply because the
> underlying objects aren't mutable. The objects *do* get passed by
> reference; the function doesn't receive a new copy of the object and
> it can examine the original object's ID. The actual culprit is not the
> way objects are passed but the assignment operator, since it works by
> rebinding names (as Andrew Koenig explained) and not by changing the
> object itself. If the swap() function could somehow access the
> underlying integer object and modify it, swapping of values would
> indeed occur because the function *did* get references to the objects
> passed to it.
> 
> That said, it's a rather convoluted way of explaining what happens and
> calling it pass-by-object feels much better. :-)
> 
The underlying point is that there is no way to rebind names in the
caller's namespace by manipulations of parameters passed as arguments to
a function.

regards
 Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/




More information about the Python-list mailing list