简体   繁体   中英

Python: Local variables mysteriously update Global variables

I have a function where I work with a local variable, and then pass back the final variable after the function is complete. I want to keep a record of what this variable was before the function however the global variable is updated along with the local variable. Here is an abbreviated version of my code (its quite long)

def Turn(P,Llocal,T,oflag):
    #The function here changes P, Llocal and T then passes those values back
    return(P, Llocal, T, oflag)

#Later I call the function
#P and L are defined here, then I copy them to other variables to save
#the initial values

P=Pinitial
L=Linitial
P,L,T,oflag = Turn(P,L,T,oflag)

My problem is that L and Linitial are both updated exactly when Llocal is updated, but I want Linitial to not change. P doesn't change so I'm confused about what is happening here. Help? Thanks!

The whole code for brave people is here: https://docs.google.com/document/d/1e6VJnZgVqlYGgYb6X0cCIF-7-npShM7RXL9nXd_pT-o/edit

The problem is that P and L are names that are bound to objects , not values themselves. When you pass them as parameters to a function, you're actually passing a copy of the binding to P and L. That means that, if P and L are mutable objects, any changes made to them will be visible outside of the function call.

You can use the copy module to save a copy of the value of a name.

Lists are mutable. If you pass a list to a function and that function modifies the list, then you will be able to see the modifications from any other names bound to the same list.

To fix the problem try changing this line:

L = Linitial

to this:

L = Linitial[:]

This slice makes a shallow copy of the list. If you add or remove items from the list stored in L it will not change the list Lintial .

If you want to make a deep copy, use copy.deepcopy .


The same thing does not happen with P because it is an integer. Integers are immutable.

In Python, a variable is just a reference to an object or value in the memory. For example, when you have a list x :

x = [1, 2, 3]

So, when you assign x to another variable, let's call it y , you are just creating a new reference ( y ) to the object referenced by x (the [1, 2, 3] list).

y = x

When you update x , you are actually updating the object pointed by x , ie the list [1, 2, 3] . As y references the same value, it appears to be updated too.

Keep in mind, variables are just references to objects.

If you really want to copy a list, you shoud do:

new_list = old_list[:]

Here's a nice explanation: http://henry.precheur.org/python/copy_list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM