- 1

Undo function in Python

I wrote a program that adds a tourism package (i.e. beginning and end dates, destination and price) to a list, can modify it and erase a specific package from the list if a condition is met (i.e. if the user inputs the 8th month of the year, the program will erase all of the packages which are in August from the list) However now I have to implement a function that undoes the last user-inputted function, so basically if I did the aforementioned instruction (deletes the packages which are in August from the list) and then I type undo, the list should be back to normal How would I proceed to do this? I thought of doing it this way first: https://pastebin.com/seqJpP6z but then I realised that I was working with packages that are dictionaries so I keep getting KeyError errors the full code is in Romanian and it's pretty long, (400+ lines) but I guess you can understand it a bit since it uses loan words mostly: https://pastebin.com/idQcpYK0

19th Oct 2021, 12:50 PM
afert
afert - avatar
7 Answers
+ 1
You could save a "snapshot" temporarily before you make any change. Either as a copy or put in another container. Another change is made, the first snapshot is deleted and the new snapshot takes it's place. When undo is called, all it'd do is load up the most recent snapshot over the current data.
19th Oct 2021, 1:08 PM
Slick
Slick - avatar
+ 1
Can you simple hold two Version of your list? One Backup and one original. Before an action on the original will be done, you create first a copy to the backup. Then change the original. And for an undo just copy the backup back to the original?
19th Oct 2021, 1:09 PM
Coding Cat
Coding Cat - avatar
+ 1
@Ipang I think that's a bit too complicated for me now hehe, I'm still a newb to python and coding :)
19th Oct 2021, 1:30 PM
afert
afert - avatar
+ 1
19th Oct 2021, 2:33 PM
Coding Cat
Coding Cat - avatar
0
@CodingCat I tried to append to a new list called "lst" every package that I deleted using the erase functions and in the undo() function I'd append to my original list "l" (lowercase L) the package from the list lst, but I keep getting an error that the list index is out of range when I append the lst[el] to the l function @Slick I tried doing this, here's the updated function and code: function: https://pastebin.com/cgJ4q4qU code : https://pastebin.com/Aszi3GVb
19th Oct 2021, 1:13 PM
afert
afert - avatar
0
Not sure whether it's feasible, but perhaps you can save deleted tourism packages into a file, and restore from it afterwards, should it be necesary. It would be a good idea to have a scheme to name the file; for example, you can combine package month with destination to name the file e.g. 08-Hawaii This way you can undo delete operation even after your program shuts down and reloads.
19th Oct 2021, 1:25 PM
Ipang
0
It's totally okay 👌 It was only an idea to cross my mind : )
19th Oct 2021, 1:31 PM
Ipang