Python advocacy in scientific computation

Greg Ewing greg at cosc.canterbury.ac.nz
Wed Mar 8 22:44:05 EST 2006


Peter Maas wrote:

> This is hard to understand for an outsider. If you pass an int, a float,
> a string or any other "atomic" object to a function you have "pass by
> value" semantics. If you put a compound object like a list or a dictionary
> or any other object that acts as an editable data container you can return
> modified *contents* (list elements etc.) to the caller, exactly like in
> Java and different from C/C++.

There's really no difference here -- when you pass an
int, you're passing a pointer to an int object, just
the same as when you pass a list, you're passing a
pointer to a list object. It's just that Python
doesn't provide any operations for changing the
contents of an int object, so it's hard to see
the difference.

The similarity is brought out by the following
example:

 >>> def a(x):
...   x = 42
...
 >>> def b(x):
...   x = [42]
...
 >>> y = 3
 >>> a(y)
 >>> print y
3
 >>> y = [3]
 >>> b(y)
 >>> print y
[3]

What this shows is that assignment to the parameter
*name* never affects anything outside the function,
regardless of whether the object passed in is mutable
or immutable.

It's best to avoid using terms like "by reference" when
talking about Python parameter passing, because it's
hard to tell whether the person you're talking to
understands the same thing by them. But if you
insist, the correct description in Algol terms is
that Python passes pointers to objects by value.

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg



More information about the Python-list mailing list