Reputation: 303
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
d[1][0].i: 7 d2[1][0].i: 6
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
d[0].i: 6 d2[0].i: 5
d[0].i: 6 d2[0].i: 6
Upvotes: 3
Views: 1119
Reputation: 20938
Here you go, straight from the docs:
import copy
class Obj:
def __init__(self, i):
self.i = i
def __deepcopy__(self, memo):
return self
Your last example doesn't seem right, as d3
is a shallow copy of d
, therefore the list indexed by 2
should remain the same reference.
To allow for deep copying as an option, you could set some attribute in the object, and check for that in __deepcopy__
.
Upvotes: 1
Reputation: 6004
You can see how the (pure python) deepcopy
and copy
methods are made here. You can try to make a simpler one for your specific objects or try to modify the "original".
You can also modify the __deepcopy__
method of your objects to return simply self
, but that might affect their behavior - if you'd like to deepcopy
them later, of course, but also if you use some external libraries, e.g. debuggers or GUI.
Upvotes: 0