Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Python function between copy() and deepcopy()

Tags:

python

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
like image 336
Matt Avatar asked Aug 27 '26 14:08

Matt


1 Answers

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__.

like image 124
simonzack Avatar answered Aug 30 '26 05:08

simonzack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!