IsString

Mike Meyer mwm at mired.org
Tue Dec 13 19:16:32 EST 2005


Steven D'Aprano <steve at REMOVETHIScyber.com.au> writes:
> But neither is it call by reference. If it were call by reference, I could
> write something like this:
>
> def increment(n):
>     """Add one to the argument changing it in place."""
>     # In Pascal, I would need the var keyword to get this behaviour,
>     # but Python is call by reference so all variables are passed 
>     # by reference.
>     n += 1
>
> x = 1
> increment(x)
> assert x == 2
>
> but that doesn't work in Python either.

Yes, it doesn't work, but the reason it doesn't work isn't because
Python doesn't do call-by-reference.

> So Python behaves demonstrably different from BOTH call by value and call
> by reference. Consequently, it is neither of them.

Right. *Python* behaves differently. That's not the same thing as
Python's calling behaving differently. If you choose objects that are
behave the same in both languages, Python behaves *exactly* like
call-by-reference.

You can show the same difference in behavior between Python and C (for
example) without using a function call.

Here's C:

#include <assert.h>

main() {
  int i, *ref ;
  i = 1 ;
  ref = &i ;	/* Save identity of i */
  i = 2 ;
  assert(ref == &i) ;
}

This runs just fine; i is the same object throughout the program.

On the other hand, the equivalent Python:

>>> i = 1
>>> ref = id(i)	# Save the identity of i
>>> i = 2
>>> assert ref == id(i)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AssertionError
>>> 

Blows up - i is no longer the same object.

Python does call by reference, which means that it passes pointers to
objects by value. C is call by value, faking call by reference by
passing reference values. The real difference is that in C, you can
get a reference to a variable to pass, allowing you to change the
variable. In python, you can't get a reference to a name (one of the
reasons we call them "names" instead of "variables"), so you can't
pass a value that will let the called function change it.

     <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list