Python function between copy () and deepcopy ()
My answer can be considered a continuation of this post .
I have a dictionary containing lists of objects. I need a function between functions copy
and deepcopy
in a module copy
. I want something that does a deep copy of Python built-in structures and primitives (integers, sets, strings, lists, etc.), but doesn't create a deep copy of user-defined objects (or non-primitive, non-aggregate objects).
It seems I might need to change the method of __deepcopy__
my objects, but I'm not entirely sure how to do this correctly. Also a solution that does not change the method of the object is preferred __deepcopy__
, in case I want to make a deep copy of the object in a future script.
Let's 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 will provide below code snippets, as well as the actual output and the desired output.
Fragment 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 result
d[1][0].i: 7 d2[1][0].i: 7
Fragment 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 result
d[0].i: 6 d2[0].i: 6
source to share
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 seems to be wrong as it d3
is a shallow copy d
, so the indexed list 2
should remain the same link.
To enable deep copying as an option, you can set some attribute on the object and check it in __deepcopy__
.
source to share
You can see how the methods of (pure python) deepcopy
and copy
are made here . You can try to make it simpler for your specific objects or try to change the "original".
You can also change the method of __deepcopy__
your objects to just return self
, but this can affect their behavior - if you want deepcopy
them later, of course, but also if you are using some external libraries like debuggers or a GUI.
source to share