Deep Copying of objects is supported in Python through the deepcopy() function of the “copy” module.
The deepcopy() method creates a new compound object and copies the members found in the original object recursively into the compound object.
Deep Copy Example:
myData = None
def __init__(self, aData):
self.myData = aData
CompoundObject = Compound([11,22,33])
DeepCopiedObject = copy.deepcopy(CompoundObject)
#add an element to the list in the CompoundObject
print("Contents of Original Compound Object")
for element in CompoundObject.myData:
print("Contents of Deep Copy Object")
for element in DeepCopiedObject.myData:
Deep Copy Output:
Contents of Original Compound Object
Contents of Deep Copy Object
As seen in the above output, after deep copy operation adding an element into the CompoundObject.myData does not affect DeepCopiedObject in any way. The reason is CompoundObject and its members have been recursively copied into the DeepCopiedObject. After the deep copy operation everything in DeepCopiedObject is distinct from CompoundObject as opposed to the shallow copy.