scope, function, mutable

Jussi Piitulainen jpiitula at ling.helsinki.fi
Tue Dec 4 12:54:04 CET 2012


gusarer at gmail.com writes:

> What is the appropriate definition for the following behavior in
> Python 2.7 (see code below).
>
> Both functions have assignment in it (like "x = ") so I assume, that
> x is a local variable in both functions.

It's a local variable in both functions because it's a formal
parameter in both. The assignments don't make any difference
here. (And a statement like x[k] = ... never does.)

> Also I thought this rule doesn't depend on WHERE in this function we
> find the assignment.

That's correct but not relevant here. It's relevant when the variable
does not occur in the function's parameter list.

> But in both functions x becomes local variable only AFTER
> assignment, so in f2 x[1] = 99 changes the global varialble (btw,
> x[3] = 99 doesn't).

In both functions, x is local from the start. Its initial value is the
same mutable object that is the value of the global variable t. The
assignments x = [44] ... give it a new value, another mutable object,
but x[k] = ... don't. The latter make a change in the old value which
is still the value of the globale variable t.

> def f1(x):
>     x = [44] + x[1:]
>     x[1] = 99
> 
> def f2(x):
>     x[1] = 99
>     x = [44] + x[1:]
>     x[3] = 99
> 
> t = [1,2,3,4,5,6,7]
> f1(t)
> print t                            # [1, 2, 3, 4, 5, 6, 7]
> t = [1,2,3,4,5,6,7]
> f2(t)
> print t                            # [1, 99, 3, 4, 5, 6, 7]

You might want to consider something like the following, because the
point really has everything to do with the fact that mutable objects
are not copied when they are passed to functions, assigned to
variables, or stored somewhere like a list, and little to do with
global vs local (other than there being different variables with the
same name).

t = [1,2,3]
u = [1,2,3]
w = u
w[1] = 0
u = t

Some people will tell you to use different words but the behaviour of
the language doesn't change.



More information about the Python-list mailing list