** I have already seen these posts, but couldn't figure out how to resolve my problem: Python: Dictionary as instance variable "Least Astonishment" and the Mutable Default Argument
I create a dictionary and then I pass it to a class as an input parameter. The class has an interal function that manipulates the value of the input dictionary. The problem is that after instantiating the class, the values of the original dictionary will also change. Here is a simple example:
class foo(object):
def __init__(self,myDict):
self.myDict = myDict
self.f()
def f(self):
for key in self.myDict.keys():
self.myDict[key] += 1
d = {'a':1,'b':2}
print 'd (before passing to the class) = ',d
inst = foo(myDict = d)
print 'inst.myDict = ',inst.myDict
print 'd (after passing to the class) = ',d
and here is the output:
d (before passing to the class) = {'a': 1, 'b': 2}
inst.myDict = {'a': 2, 'b': 3}
d (after passing to the class) = {'a': 2, 'b': 3}
As you can see the value of the original dictionary "d" has also changed after instantiating the class. How can I avoid this? I need to institute this class with d several times (while changing other input parameters) and don't want to redefine "d" every time I instantiate.