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
barfunction, 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 firstbarfunction, on the other hand, you assign a different object to the namefooinside the function when you writefoo = "bar". When you do that, the namefooinside the function starts to refer to the string"bar"and not to the string"foo". You’ve changed which object the name refers to. Butfooinside the function andfoooutside the function are different names, so if you change the object labeled byfooinside the function, you don’t affect the namefoooutside the function. So they refer to different objects.