anything like C++ references?

Jimmy Retzlaff jimmy at retzlaff.com
Sun Jul 13 17:45:45 EDT 2003


Stephen Horne wrote:
>...
>Of course, if you really believe that pointer/reference behaviour
>should be arbitrarily tied to mutability then you can claim that I am
>wrong, but you still can't claim the high ground as this is still an
>arbitrary and bizarre thing to do. The ability to change part or all
>of a value in-place has nothing to do with whether that value is
>referenced using a pointer or whatever in computer theory - any link
>between pointers/references and mutability should be related to the
>implementation of the language - not the semantics.
>...

Assignment, and therefore parameter passing, is entirely consistent
between mutable/immutable types. That is to say, assignment and
mutability are orthogonal and unrelated concepts in Python, just as you
suggest they should be. Perhaps some folks who only partially understand
Python's parameter passing semantics would be surprised by:

>>> def f(x):
... 	x = [4, 5, 6]
... 	
>>> a = [1, 2, 3]
>>> f(a)
>>> print a
[1, 2, 3]

Note that the assignment within f did not affect a in any way despite
the fact that a was an instance of a mutable type. It works exactly the
same way with a tuple.

With similar consistency you can call any method on an object passed as
a parameter. Where the distinction between mutable and immutable types
comes in is that there don't happen to be any methods of immutable
objects that actually modify the value of the object; mutable objects do
offer such methods. For example, tuples don't have "append" or "sort"
methods that modify the object's value in place, but lists do.

Now where some more of the assignment related confusion might come in is
with things like this:

>>> def f(x):
... 	x[0] = 10
... 	
>>> a = [1, 2, 3]
>>> f(a)
>>> print a
[10, 2, 3]

The body of f may look like it contains an assignment, but that's not
the typical name-binding that is referred to when discussing assignment
(or parameter passing) in Python. That is really just syntactic sugar
for calling a method of the parameter x, namely the __setitem__ method.
List objects are mutable and so, by definition, some methods like
__setitem__ will change their value. Tuples don't have __setitem__
methods so the above assignment in f won't work if you pass in a tuple.
Note that the same "assignment" outside of f wouldn't work for a tuple
either; this is a property of the tuple (i.e., it doesn't offer a
__setitem__ method), not of Python's parameter passing / assignment
semantics.

Jimmy





More information about the Python-list mailing list