Mutability of function arguments?

bruno at modulix onurb at xiludom.gro
Thu Dec 8 04:41:08 EST 2005


ex_ottoyuhr wrote:
> I'm trying to create a function that can take arguments, say, foo and
> bar, and modify the original copies of foo and bar as well as its local
> versions -- the equivalent of C++ funct(&foo, &bar).

This is already what you have. In Python, all you have are references to
objects, there is no "local version".

> I've looked around on this newsgroup and elsewhere, and I gather that
> this is a very common concern in Python, but one which is ordinarily
> answered with "No, you can't. Neat, huh?" 

Pardon ???

>>> def appendToList(aList, aValue):
...     aList.append(aValue)
...
>>> mylist = range(10)
>>> mylist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> appendToList(mylist, 42)
>>> mylist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 42]
>>>

Now the usual considerations apply :
- rebinding an arg has of course only local effect
- immutable objects are still immutables

Also note that since
1/ Python as a good support for exception handling
2/ a function can return multiple values [1],
there is less need for such constructs than in C or C++.

[1] the truth is that the function can return a unique tuple, that can
be unpacked as any other.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list