Search code examples
pythonarraysrestore

Un-edit an array to how it was when it was created


I have a 2D array which is edited at certain points throughout my program. When I get to a certain point in my program, I would like to 'un-edit' the array so it is as it was when the array was created. e.g.

myArray = [[0, 0, 0, 0], # myArray as it is programmed in my script 
           [0, 2, 0, 2]]
... #Code runs, array is edited.

now my array looks like...

[[0, 0, 0, 0],
 [0, 0, 0, 0]]

and then an event happens which causes me to want to change my array back to its original state. I could create a copy of myArray at the beginning of the program and load that, but that would be very impractical as I have tens of similar arrays which need to act the same way, and I may need to un-edit the arrays more than once, which would mean I would have hundreds of copies. I don't know any way to do this practically.


Solution

  • I would adopt a "copy on write" approach:

    1. Reset will point back to the original array which is a single instance for all.
    2. Editing an array will create a copy from the original one. Then modifying it won't affect the original instance.
    original = [[0, 0, 0, 0], [0, 2, 0, 2]]
    def edit(my_array):
        if id(my_array) == id(original):
            my_array = original.copy()
        # ... edit the array
    
    def reset(my_array):
        my_array = original
    

    where my_array is the actual working copy that can be edited and is different between users.