Mutability of function arguments?

Fredrik Lundh fredrik at pythonware.com
Wed Dec 7 19:29:54 EST 2005


"ex_ottoyuhr" wrote:

> 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?

anyone that holds a reference to a mutable object can modify it, and
everyone that has the same reference will see the changes.  assignment
copies references, not values:

    >>> foo = []
    >>> value = foo
    >>> foo.append("hello")
    >>> foo.append("world")
    >>> value
    ['hello', 'world']

> 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 self.foo is a mutable object, and your function is modifying it in
place, yes:

    >>> class FooWrapper:
    ...     def __init__(self, fooToLoad):
    ...             self.foo = fooToLoad
    ...
    >>> value = []
    >>> foo = FooWrapper(value)
    >>>
    >>> foo.foo
    []
    >>> value
    []
    >>> def mutator(x):
    ...     x.foo.append("hello")
    ...
    >>> mutator(foo)
    >>> mutator(foo)
    >>>
    >>> foo.foo
    ['hello', 'hello']
    >>> value
    ['hello', 'hello']

however, if the mutator replaces the wrapped object, the original object
will not see the changes.  you can still see them via the wrapper, of course:

    >>> def mutator(x):
    ...     x.foo = ["goodbye"]
    ...
    >>> mutator(foo)
    >>> foo.foo
    ['goodbye']
    >>> value
    ['hello', 'hello']

this might help:

    http://effbot.org/zone/python-objects.htm

</F>






More information about the Python-list mailing list