scope, function, mutable

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Dec 4 12:32:41 CET 2012


On Tue, 04 Dec 2012 14:55:44 +0400, gusarer wrote:

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

Well, yes, but that's not why x is local in this case. In this case, x is 
local because the name of the function parameter is "x", and function 
parameters are always local.



> Also I thought this rule doesn't depend on WHERE in this function we
> find the assignment.
> 
> But in both functions x becomes local variable only AFTER assignment, 

Not so. Read on.

> so
> in f2 x[1] = 99 changes the global varialble (btw, x[3] = 99 doesn't).
> 
> def f1(x):
>     x = [44] + x[1:]
>     x[1] = 99

When you call f1(t), with t a global list, Python passes the list object 
to the function and binds it to name x. The function gets executed like 
this pseudo-code:

# calling f1(t)
pass object known as "t" to the function
bind that object to the local name "x"
create a new list: [44] + a slice of x
bind this new list to name "x"
modify in place item 1 of the new list known as "x"


Notice that the only *modification* occurs after a new list is created 
and bound to the name "x", so the modification does not change the 
original, global, list.


But now consider your other function:

> def f2(x):
>     x[1] = 99
>     x = [44] + x[1:]
>     x[3] = 99

In pseudo-code again:

# calling f2(t)
pass object known as "t" to the function
bind that object to the local name "x"
modify in place item 1 of the list known as "x", 
    which is another name for the global list known as "t"
create a new list: [44] + a slice of x
bind this new list to name "x"
modify in place item 3 of the new list known as "x"

So in this case you have to in-place modifications. The first occurs 
while the name "x" still refers to the original list, and so it modifies 
the original list. The second occurs after the name "x" has been rebound 
to a new list, and so it doesn't change the original.



-- 
Steven



More information about the Python-list mailing list