Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to selectively deep-copy in python?

I have multiple python classes. Objects of one of the classes (say, class1)has a large amount of data in it (it will not be altered during runtime). Another class (say class2) has a member variable which maps to one of the objects of class1. Assume class1 and class2 have other both mutable and immutable member variables.

Now i want too do a deepcopy of an object of class2. It will also make a deepcopy of the class1 object in class2. but to save memory, i want to avoid that. how do i do this?

class class1:
    def __init__(self):
        self.largeData = None
        self.mutableVar = None
        self.immutableVar = None


class class2:
    def __init__(self, objc1: class1):
        self.objc1 = objc1  # of the type class1
        self.mutableVar = None
        self.immutableVar = None


c1_1 = class1()
c1_2 = class1()

c2_1 = class2(c1_1)

c2_1Copy = copy.deepcopy(c2_1)
# i want c2_1Copy to reference the same objc1 as c2_1,
# but different mutablevar and immutablevar

c2_2 = class2(c1_2)  # Note: cannot use static variable

please help me with this...
thanks in Advance

like image 575
santhanam srinivasan Avatar asked Nov 24 '25 13:11

santhanam srinivasan


1 Answers

Use the __deepcopy__ hook method to customize how your objects are deep-copied.

import copy


class LargeDataContainer:
    def __init__(self):
        self.data = "x" * 800


class Thing:
    def __init__(self, large_data: LargeDataContainer):
        self.large_data = large_data
        self.x = [1, 2, 3]

    def __deepcopy__(self, memo):
        new_inst = type(self).__new__(self.__class__)  # skips calling __init__
        new_inst.large_data = self.large_data  # just assign

        # rinse and repeat this for other attrs that need to be deepcopied:
        new_inst.x = copy.deepcopy(self.x, memo)
        return new_inst


ldc = LargeDataContainer()

t1 = Thing(ldc)
t2 = copy.deepcopy(t1)
assert t1 is not t2
assert t1.large_data is t2.large_data
assert t1.x is not t2.x

like image 60
AKX Avatar answered Nov 26 '25 04:11

AKX



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!