I am designing a class that has undo/redo functionality and has to temporarily store a lot of data. I'm currently implementing a "temporary" file by overloading the del operator to delete the file when the class is garbage collected, but I have to believe there is a better way to do this. I have tried using the tempfile module, but it doesn't work because the shelve module expects a name, not a file object (grr).
Anyway, was wondering if anyone had a better way to do this. Important parts of the code are below.
import os, shelve
from time import time
class DataHandlerUser(DataHandler):
def __init__(self, data):
# storing items
self.__unredofilename = os.path.dirname(__file__) + '/.undoredo' + str(time()) + '.pyworkbooks'
try:
os.remove(self.__unredofilename)
except OSError: pass
self._undoredoBuffer = shelve.open(self.__unredofilename)
# ... rest of init
def __del__(self):
# simple check to make sure not tampered with
if '.undoredo' not in self.__unredofilename or '.pyworkbooks' not in self.__unredofilename:
raise Exception('Critical Error: Internal filename for undo/redo operations tampered with')
try:
os.remove(self.__unredofilename)
except OSError: pass