foo = "foo" def bar(foo): foo = "bar"
bar(foo)
print foo
# foo is still "foo"...
foo = {'foo':"foo"}
def bar(foo):
foo['foo'] = "bar"
bar(foo)
print foo['foo']
# foo['foo'] is now "bar"?
I have a function that has been inadvertently over-writing my function parameters when I pass a dictionary. Is there a clean way to declare my parameters as constant or am I stuck making a copy of the dictionary within the 开发者_运维知识库function?
Thanks!
In a case like this, you'd have to copy the dictionary if you want to change it and keep the changes local to the function.
The reason is that, when you pass a dictionary into your second bar
function, Python only passes a reference to the dictionary. So when you modify it inside the function, you're modifying the same object that exists outside the function. In the first bar
function, on the other hand, you assign a different object to the name foo
inside the function when you write foo = "bar"
. When you do that, the name foo
inside the function starts to refer to the string "bar"
and not to the string "foo"
. You've changed which object the name refers to. But foo
inside the function and foo
outside the function are different names, so if you change the object labeled by foo
inside the function, you don't affect the name foo
outside the function. So they refer to different objects.
Arguments are passed by value, but in this case the value is a reference to an object. This is also called call by sharing. So yes, if you need a new dictionary, you will have to create one in the function.
I would like to add that
temp_dict = CONSTdict
did not help, as this simply copies the pointer.
Instead, I needed:
temp_dict = dict(CONSTdict)
Cheers,
Shaun
精彩评论