deepcopy function in Python

deepcopy() in python creates a new compound object and copies the members of the original object recursively into the new compound object

Copy Updated 22 Jan 2017 1 min read

Deep Copy

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

python
import copy

class Compound:

    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

CompoundObject.myData.append(44)

print("Contents of Original Compound Object")

print("===================================")

for element in CompoundObject.myData:

    print(element)

print("===================================")

print("Contents of Deep Copy Object")

print("===================================")

for element in DeepCopiedObject.myData:

    print(element)

Deep Copy Output

Output
Contents of Original Compound Object

===================================

11

22

33

44

===================================

Contents of Deep Copy Object

===================================

11

22

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.