I want to create an undo()
function that undoes the last operation in python, so I just deepcopied the list before any modifications were made during whatever function to another list (I made a bootleg deepcopy
by myself), called undolist
, and then when I call undo()
I just pop the last element from the undolist
I know there are other more efficient ways of doing this, but given my time constraints and my mental in-capabilities I don't think I could turn this in.
However, it doesn't work. I am going to post an example of how I implemented the undo function and the bootleg deepcopy
on a random function, since the code itself is super long and in another language
I hope I've made myself clear enough, if there are any misunderstandings I'll edit the post.
main_list = [list of lists that have elements in them]
def bootleg_deepcopy(main_list):
new_list = []
for x in main_list:
nx = x[:]
new_list.append(nx)
return new_list
def delete_elements(main_list,user_input,undolist):
#function that deletes elements from the list if a condition isn't met
undolist.append(bootleg_deepcopy(main_list))
main_list[:] = [element for element in main_list if not function_that_checks_something(whatever,something)]
return main_list
def undo(main_list,undolist):
try:
main_list = undolist.pop()
except Exception as ex:
print(ex)
return main_list
CodePudding user response:
Your undo simply returns a new reference to main_list. Your delete_elements method overwrites the main_list in-place (main_list[:] = ...
). I assume you want the same behavior in your undo action so that all places that hold references to main_list are updated automatically.
CodePudding user response:
The solution was to use the slice operator(?) in the undo()
function. I've edited it so that it includes the right code.
def undo(main_list,undolist):
try:
main_list[:] = undolist.pop()
except Exception as ex:
print(ex)
return main_list