[Tutor] Still confused about Python references/objects

Sheila King sheila@thinkspot.net
Sat, 31 Mar 2001 16:20:12 -0800


On Sat, 31 Mar 2001 14:52:00 -0500, "Tim Peters" <tim.one@home.com>  wrote
about RE: [Tutor] Still confused about Python references/objects:

:[Sheila King]
:> ...
:> However, just for illustration, I was trying to write a swap
:> function. And, I thought that all parameters were passed by reference.
:
:"by reference" isn't really a useful concept in Python.  People bring that
:with them from other languages, and get into all sorts of trouble trying to
:force it to fit.

You're telling me! (I bring background experience from a few different
languages: Pascal, Fortran, VB, C++, and they ALL behaved that way! It is so
difficult to get used to this new way of thinking.)

:  Python is *simpler* than that.  It's easier (in the end
:<wink>) to think of argument-passing in Python as being "pass by object":
:don't think of passing names, or pointers, or references, or even values, but
:think of passing objects directly.

OK...

...<snipped>...

:The other half of the story is that a statement of the form
:
:    x = y
:
:is *not* an operation on objects, it's an operation on namespaces, and all it
:means is "whatever object the name 'y' refers to at this moment, also give
:that object the name 'x' (and in the local namespace, provided 'x' hasn't
:been declared global)".
:
:Argument passing is exactly like
:
:    x = y
:
:in all respects:  the objects in the argument list are merely given names in
:the called function's local namespace.  The names they're given are, of
:course, the function's formal argument names.

...<very good explanation snipped>...

OK, so I think I get what you're saying. It sounds like, in order to have a
function modify an object in the calling functions space, either it has to be
a mutable object, or else I would (I think?) have to return the new version I
want, and assign it to a name in the calling function's namespace ???

Does this sound right?

So, now I think I know what I'm doing, and I try this:

>>> def swap(two_tuple):
	x,y = two_tuple
	return y, x

>>> a = 2
>>> b = 3
>>> print a, " ", b
2   3
>>> a,b = swap((a,b))
>>> print a, " ", b
3   2
>>> 

OK, I think I got it. The only way to think of a function as modifying
something in the calling namespace, is either if it is a mutable object, or
else it has to return the new object that I want to reference.

--
Sheila King
http://www.thinkspot.net/sheila/
http://www.k12groups.org/