Mutable parameters to functions

Fredrik Lundh fredrik at pythonware.com
Wed Dec 15 07:58:21 EST 1999


Alwyn Schoeman <alwyns at prism.co.za> wrote:
> I've been working through Mark and David's book Learning Python.
> 
> On page 105 there is an example that states that when you change
> a argument that is mutable in place (thew!) then you also change
> the value of the variable in the callers namespace.
> 
> Ok, now on page 107 there is an example on returning multiple
> values.  The code is as follows:
> def multiple(x,y):
>     x = 2
>     y = [3,4]
>     return x, y
> 
> X = 1
> L = [1, 2]
> X, L = multiple (X, L)
> X, L
> 
> result is then (2, [3, 4])
>
> Now, the question is whether the statement y = [3, 4] constitutes
> an inplace change of the global variable L?

nope.  a plain assignment never modifies a variable
(it only changes the name binding in the relevant
namespace)

in this example, it's the "X, L = multiple" assignment
that replaces (rebinds) the value of L.

if another variable points to the same list, it's not
affected.

likewise, if you change the last two lines to:

> X, Y = multiple (X, L)
> X, Y, L

you get:

(2, [3, 4], [1, 2])

> would  X = multiple(X,L) yield the same results?

yes or no, depending on what you mean ;-)

(yes, the assignment inside "multiple" doesn't
modify the global variable.  or no, if you print
both X and L as in the example, you get diff-
erent output...)

...

summary:

the *ONLY* way to modify an object in place is to call
a method on it.

    X.append(1)

this includes syntactic sugar:

    X.member = 1 # calls X.__setattr__
    X[0] = 1 # calls X.__setitem__
    del X[1:3] # calls X.__delslice__
    # etc

but not plain assignment statements.

hope this helps!

</F>

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list