SwimBikeRun
SwimBikeRun

Reputation: 4460

Python's Deep copy doesn't make copy of dictionary inside new instances of objects

I want to copy an object (contains a dictionary). I plan to pass this object along in a recursion tree and I want each node in the tree receiving a new copy, not a linked copy.

I discovered that the dictionaries inside the objects "new_t1" and "new_t2" are the same, even though the object ID is different.

Is there an easy way to create a true deep copy of an object, or do I have to write my own to get around it just assigning a pointer to the same dictionary?

hcPartial is a class containing a dictionary and a few other things:

class hc:

    dictionary = {'00':[], '01':[], '10':[], '11':[]}

Code illustrating failure:

#Check making two hypercube copies and independently adding to one of them
nhc1 = copy.deepcopy(hcPartial)
nhc2 = copy.deepcopy(hcPartial)

print "ID 1: ", id(nhc1), "ID 2: ", id(nhc2)
print "D ID 1: ", id(nhc1.dictionary), "D ID 2: ", id(nhc2.dictionary)
print nhc1.dictionary
nhc1.forwardConnect('00','01')
print nhc1.dictionary
print nhc2.dictionary
print nhc1
print nhc2

Output:

ID 1:  92748416 ID 2:  92748696
D ID 1:  92659408 D ID 2:  92659408
{'11': [], '10': [], '00': [], '01': []}
{'11': [], '10': [], '00': ['01'], '01': []}
{'11': [], '10': [], '00': ['01'], '01': []}
<hypercube.HyperCube2D instance at 0x05873A80>
<hypercube.HyperCube2D instance at 0x05873B98>

Intended Output:

{'11': [], '10': [], '00': [], '01': []}
{'11': [], '10': [], '00': ['01'], '01': []}
{'11': [], '10': [], '00': [], '01': []}

Corrected Output added __init__() in class. Works!

ID 1:  92746056 ID 2:  92730952
Dict ID 1:  92665728 Dict ID 2:  92680240
{'11': [], '10': [], '00': [], '01': []}
forwardConnect ID 1:  91704656 forwardConnect ID 2:  91704656
{'11': [], '10': [], '00': ['01'], '01': []}
{'11': [], '10': [], '00': [], '01': []}
<hypercube.HyperCube2D instance at 0x05873148>
<hypercube.HyperCube2D instance at 0x0586F648>

Upvotes: 0

Views: 558

Answers (1)

Paul Sweatte
Paul Sweatte

Reputation: 24617

As noted above:

The problem turned out being that my class didn't have an

__init__() 

in it.

If you want each instance to have its own dictionary, you should move its initialization from the class level into a method:

 __init__(): 
 self.dictionary = ... 

References

Upvotes: 1

Related Questions