1
In the code below the dictionary used as input argument is also being modified by the function. I need to perform a deepcopy()
at all times?
def muda(a):
a['valor'] = 50
return a
dic1 = {'valor': 12}
dic2 = muda(dic1)
print(dic1)
{'valor': 50}
print(dic2)
{'valor': 50}
from copy import deepcopy
dic1 = {'valor': 12}
dic2 = muda(deepcopy(dic1))
print(dic1)
{'valor': 12}
print(dic2)
{'valor': 50}
Dictionary is a changeable type, so its passage through the parameter is by reference. If it makes sense to change the value within the function, but you don’t want this change to be reflected out of the function, you actually have to copy the object.
– Woss