Problem with assigning variables of type List

Hans Nowak wurmy at earthlink.net
Wed Aug 21 05:46:00 CEST 2002


I really should know better than posting in this thread, but here goes... :-/

Paul Foley wrote:

>   CALL-BY-VALUE:
>   
>   (CBV) An evaluation strategy where arguments are evaluated before
>   the function or procedure is entered.  Only the values of the
>   arguments are passed and changes to the arguments within the called
>   procedure have no effect on the actual arguments as seen by the
>   caller. See applicative order reduction, call-by-value-result,
>   strict evaluation, call-by-name, lazy evaluation.
> 
> So: arguments are evaluated before the function or procedure is
> entered?  Yup, Python does that.  Only the values are passed, and
> changes to the arguments within the called procedure have no effect on
> the actual arguments as seen by the caller?  Right again.  Python
> meets that definition.  I guess it's call-by-value (what a surprise!)

Umm... changes to the arguments do seem to affect them as seen by the caller. 
At least for mutable objects:

 >>> def foo(lst):
	lst.append(42)
	
 >>> a = [1,2,3]
 >>> a
[1, 2, 3]
 >>> foo(a)
 >>> a
[1, 2, 3, 42]

I guess one could argue that the "value" passed here is an object, in this case 
the list object, and the identity of that object cannot be changed by the 
function in such a way that the caller ends up with a different object. The 
id() of list a in the example is the same before and after the call.

However, by that line of reasoning, C doesn't have call by reference either:

void foo(int *a)
{
     *a = 42;
}

(I hope the syntax is right, my C is a bit rusty.)

By this reasoning, the above is obviously call by value as well. The value 
being passed is a pointer, and the function isn't capable of changing the 
pointer; it is capable of changing the integer it points to, but that's 
something different.

However, that is not what FOLDOC says:

>   CALL-BY-REFERENCE
> 
>   An argument passing convention where the address of an argument
>   variable is passed to a function or procedure, as opposed to where
>   the value of the argument expression is passed. Execution of the
>   function or procedure may have side-effects on the actual argument
>   as seen by the caller. The C language's "&" (address of) and "*"
>   (dereference) operators allow the programmer to code explicit
>   call-by-reference. 

If you accept that C can do call by reference, then so can Python.

> So, the address of the argument variable is passed?  Not in Python[1].
> Execution of the function or procedure may have side-effects on the
> actual argument as seen by the caller?  Not in Python.  

See my example code...

-- 
Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA=='))
# decode for email address ;-)
The Pythonic Quarter:: http://www.awaretek.com/nowak/
Kaa:: http://www.angelfire.com/jazz/aquila/blog/blogger.html




More information about the Python-list mailing list