@@ -28,15 +28,18 @@ def __copy__(self):
28
28
`copy.copy` with this object and the returned value is returned as the
29
29
new shallow copy.
30
30
"""
31
+
32
+ # First, let's create copies of the nested objects.
33
+ some_list_of_objects = copy .copy (self .some_list_of_objects )
34
+ some_circular_ref = copy .copy (self .some_circular_ref )
35
+
36
+ # Then, let's clone the object itself, using the prepared clones of the
37
+ # nested objects.
31
38
new = self .__class__ (
32
- self .some_int , self . some_list_of_objects , self . some_circular_ref
39
+ self .some_int , some_list_of_objects , some_circular_ref
33
40
)
34
41
new .__dict__ .update (self .__dict__ )
35
42
36
- # The new object has a new list of objects but with same
37
- # objects(shared).
38
- new .some_list_of_objects = copy .copy (self .some_list_of_objects )
39
- new .some_circular_ref = copy .copy (self .some_circular_ref )
40
43
return new
41
44
42
45
def __deepcopy__ (self , memo = {}):
@@ -51,15 +54,18 @@ def __deepcopy__(self, memo={}):
51
54
to all the `deepcopy` calls you make in the `__deepcopy__` implementation
52
55
to prevent infinite recursions.
53
56
"""
57
+
58
+ # First, let's create copies of the nested objects.
59
+ some_list_of_objects = copy .deepcopy (self .some_list_of_objects , memo )
60
+ some_circular_ref = copy .deepcopy (self .some_circular_ref , memo )
61
+
62
+ # Then, let's clone the object itself, using the prepared clones of the
63
+ # nested objects.
54
64
new = self .__class__ (
55
- self .some_int , self . some_list_of_objects , self . some_circular_ref
65
+ self .some_int , some_list_of_objects , some_circular_ref
56
66
)
57
67
new .__dict__ .update (self .__dict__ )
58
68
59
- # The new object has a new list of objects with different copy of those
60
- # objects.
61
- new .some_list_of_objects = copy .deepcopy (self .some_list_of_objects , memo )
62
- new .some_circular_ref = copy .deepcopy (self .some_circular_ref , memo )
63
69
return new
64
70
65
71
@@ -138,11 +144,11 @@ def __deepcopy__(self, memo={}):
138
144
139
145
print (
140
146
f"id(deep_copied_component.some_circular_ref.parent): "
141
- "{id(deep_copied_component.some_circular_ref.parent)}"
147
+ f "{ id (deep_copied_component .some_circular_ref .parent )} "
142
148
)
143
149
print (
144
150
f"id(deep_copied_component.some_circular_ref.parent.some_circular_ref.parent): "
145
- "{id(deep_copied_component.some_circular_ref.parent.some_circular_ref.parent)}"
151
+ f "{ id (deep_copied_component .some_circular_ref .parent .some_circular_ref .parent )} "
146
152
)
147
153
print (
148
154
"^^ This shows that deepcopied objects contain same reference, they "
0 commit comments