python copy class object code example

Example: python copy class object

"""
I've read that there are problems with this approach, but it never let me down
"""

import copy

class Dummy:
    def __init__(self, signature = 1, some_list = []):
        self.signature = signature
        self.list = some_list

    def change_signature(self):
        self.signature += 1

    def change_list(self):
        self.list[0][0] += 1


def naive_test():
    print('---> Naive Copy Test')
    dummy1 = Dummy(1)
    #dummy2 points to dummy1
    dummy2 = dummy1
    if dummy1.signature == dummy2.signature:
        print ('\tDummy instances are the same')
    dummy1.change_signature()
    if dummy1.signature == dummy2.signature:
        print ('\tDummy \'copy\' changed after changing the original. They are still the same.')

def shallow_copy_test():
    print('\n---> Shallow Copy Test')
    dummy1 = Dummy(1, [[1,2],[3,4]])
    #Create shallow copy
    dummy2 = copy.copy(dummy1)
    if dummy1.signature == dummy2.signature:
        print ('\tDummy instances are the same')
    dummy1.change_signature()
    if dummy1.signature != dummy2.signature:
        print ('\tDummy copy didn\'t change after changing the original. They are now different.')
    dummy1.change_list()
    if dummy1.list == dummy2.list:
        print('\tBut their lists change together! This is because the copy only made copies of the original instance\'s higher level list, but it is a list of lists, so each instance points to two different lists which, in turn, point to the SAME lists')

def deep_copy_test():
    print('\n---> Deep Copy Test')
    dummy1 = Dummy(1, [[1,2],[3,4]])
    #Create deep copy
    dummy2 = copy.deepcopy(dummy1)
    if dummy1.signature == dummy2.signature and dummy1.list == dummy2.list:
        print ('\tDummy instances are the same')
    dummy1.change_list()
    if dummy1.list != dummy2.list:
        print('\tNow each instance is 100% independent. Deep copy goes through all nested references!')


naive_test()
shallow_copy_test()
deep_copy_test()

Tags:

Misc Example