Today a colleague told me he implemented a Recent Files list in the File menu of a tool he is working on. He simply used a list that collects the recent file paths from a file and appends new entries as the user opens new files. If an entry already exists in the list, it would remove it and append the entry again, so it would be on the end of the list. The list itself is displayed in reverse order in the application, so everything works as you would expect. We talked a bit about other ways to implement this in Python and I thought it would be nice to extend the builtin list:
class RecentList(list): def append(self, entry): if entry in self: self.remove(entry) self.insert(0, entry)
and then use it like:
recent = RecentList(["c.txt", "b.txt", "a.txt"]) print ("Left to right from most to least recent:") print (recent) print ("Add existing entry b.txt:") recent.append("b.txt") print (recent) print ("Add existing entry c.txt:") recent.append("c.txt") print (recent)
I love that it is so simple in Python to customize existing things like this. There are probably more things to consider for a serious implementation, like operators etc., but for that special case it already does what is needed and it’s explicit.