Mutability of function arguments?
mwm at mired.org
Thu Dec 8 02:55:04 CET 2005
"ex_ottoyuhr" <ex_ottoyuhr at hotmail.com> writes:
> 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).
C++'s '&' causes an argument to be passed by reference. Python does
that with all arguments. Any changes you make to the argument in the
function will be seen in the caller unless you explicitly make a copy
> 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?
If your arguments are mutable, you don't need to do anything to be
able to change them - just call the mutator methods. If your arguments
aren't mutable, then you can't change them, either in the function or
in the original namespace.
If what you really want to do is rebind a variable in the calling
namespace - well, you can't do that. The standard way to deal with the
usual uses for passing references in C is to return the value (or
values - Python handles multi-valued return and assignment much
cleaner than C++) and rebind the variables at the point of the call.
If you insist on writing C/C++ in Python, you can wrap an immutable
object in an instance of class with a method to let you change it, as
> 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?
If you like an extended lambda calculus syntax, you can use my Ref
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