My response can be considered a follow-up to this post.
I have a dictionary that contains lists of objects. I want some function in between the copy
and deepcopy
functions in the copy
module. I want something that performs a deep copy on built-in Python structures and primitives (integers, sets, strings, lists, etc.) but doesn't produce a deep copy of user-made objects (or non-primitive, non-aggregate objects).
It seems I might need to modify the __deepcopy__
method of my objects, but I'm not quite sure how to do this properly. A solution that does not modify an object's __deepcopy__
method is also preferable, in the event that I want to make a deep copy of the object in a future script.
Assume this is the top of my Python file:
import copy
class Obj():
def __init__(self,i):
self.i = i
pass
d = {0:Obj(5),1:[Obj(6)],2:[]}
d2 = copy.deepcopy(d)
As examples, I'll list some code snippets below, along with the actual output and the desired output.
Snippet 1
d[1][0].i=7
print "d[1][0].i:",d[1][0].i,"d2[1][0].i:",d2[1][0].i
- Actual Output:
d[1][0].i: 7 d2[1][0].i: 6
- Desired Output
d[1][0].i: 7 d2[1][0].i: 7
Snippet 2
d[0].i = 6
print "d[0].i:",d[0].i,"d2[0].i:",d2[0].i
- Actual Output:
d[0].i: 6 d2[0].i: 5
- Desired Output
d[0].i: 6 d2[0].i: 6