Mutability of function arguments?

Brett g Porter bgporter at acm.org
Wed Dec 7 20:20:34 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).
> 
> 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?" A few websites, newsgroup
> posts, etc. have recommended that one ask for a more "Pythonic" way of
> doing things; so, is there one, or at least one that doesn't involve
> using objects as wrappers for mutable arguments?
> 
> And, indeed, would that approach work? Would declaring:
> 
> class FooWrapper :
>     __init__(fooToLoad) :
>         self.foo = fooToLoad
> 
> mean that I could now declare a FooWrapper holding a foo, pass the
> FooWrapper to a function, and have the function conclude with the foo
> within the FooWrapper now modified?

Well, you can test it yourself:

 >>> class wrapper(object):
...    def __init__(self, val):
...       self.val = val
...
 >>> w = wrapper(42)
 >>> w.val
42
 >>> def foo(w):
...    w.val = 11
...
 >>> foo(w)
 >>> w.val
11
 >>>

> 
> Thanks in advance for everyone's time; I hope I'm comprehensible.

You're comprehensible, but I think that you're also thinking in C++.
The object model that Python follows is very different --  instead of
thinking of assignment meaning
"Stick this value into this named location", you need to switch to 
thinking of assignment as meaning "stick this name onto that object 
until I tell you otherwise".

If you're trying to return multiple values from a function, Python lets 
you do that

 >>> def multiFoo(x, y, z):
...    return x*2, y*2, z*2
...
 >>> x = 1
 >>> y = 2
 >>> z = 3
 >>> x, y, z = multiFoo(x, y, z)
 >>> x
2
 >>> y
4
 >>> z
6
 >>>
-- 
//  Today's Oblique Strategy (© Brian Eno/Peter Schmidt):
//  Repetition is a form of change
//  Brett g Porter * BgPorter at acm.org




More information about the Python-list mailing list