Shallow copy in Python

Shallow Copy:

When a copy of an object is made a shallow copy means a new compound object is created but only the references of the original object (as opposed to copying all the contents recursively as in deep copy) are copied into the new compound object.

Thus the new compound object created is only a shallow copy of the original object.

Shallow Copy Example:

import copy

 

class Compound:

       

    myData = None

 

    def __init__(self, aData):

        self.myData = aData

 

CompoundObject  =  Compound([60,70,80,90])

ShallowCopy     =  copy.copy(CompoundObject)

 

#add an element to the list in the CompoundObject

 

CompoundObject.myData.append(100)

 

# Print ShallowCopy to verify it just refers to the original CompoundObject

# for its contents

print("Contents of Original CompoundObject")

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

 

for element in CompoundObject.myData:

    print(element)

               

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

print("Contents of ShallowCopy Object")

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

for element in ShallowCopy.myData:

    print(element)

 

 

Shallow Copy Output:

 

Contents of Original CompoundObject

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

60

70

80

90

100

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

Contents of ShallowCopy Object

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

60

70

80

90

100

In the above example printing CompoundObject.myData and ShallowCopy.myData produce the same output. Because,

ShallowCopy     =  copy.copy(CompoundObject)

Only creates new object ShallowCopy. The members of the CompoundObject are simply made as references in the ShallowCopy.

Hence myData in CompoundObject and myData in ShallowCopy are the references to same objects.


Copyright 2024 © pythontic.com