diff --git a/src/structures.py b/src/structures.py index 8c6f05c98..090680d11 100644 --- a/src/structures.py +++ b/src/structures.py @@ -38,6 +38,7 @@ Data structures for Python. import fix import types +import string class RingBuffer(object): """Class to represent a fixed-size ring buffer.""" @@ -340,3 +341,30 @@ class TwoWayDictionary(dict): value = self[key] dict.__delitem__(self, key) dict.__delitem__(self, value) + + +class PersistentDictionary(dict): + _trans = string.maketrans('\r\n', ' ') + _locals = locals + _globals = globals + def __init__(self, filename, globals=None, locals=None): + mylocals = locals + myglobals = globals + if mylocals is None: + mylocals = self._locals() + if myglobals is None: + myglobals = self._globals() + self.filename = filename + try: + fd = file(filename, 'r') + s = fd.read() + fd.close() + s.translate(self._trans) + super(self.__class__, self).__init__(eval(s, myglobals, mylocals)) + except IOError: + pass + + def close(self): + fd = file(self.filename, 'w') + fd.write(repr(self)) + fd.close() diff --git a/test/test_structures.py b/test/test_structures.py index ad92ee81d..aeddc70da 100644 --- a/test/test_structures.py +++ b/test/test_structures.py @@ -574,6 +574,19 @@ class TwoWayDictionaryTestCase(unittest.TestCase): del d['bar'] self.failIf('bar' in d) self.failIf('foo' in d) + + +class PersistentDictionaryTestCase(unittest.TestCase): + def test(self): + d = PersistentDictionary('test.dict') + d['foo'] = 'bar' + d[1] = 2 + d.close() + d1 = PersistentDictionary('test.dict') + self.failUnless('foo' in d) + self.assertEqual(d['foo'], 'bar') + self.failUnless(1 in d) + self.assertEqual(d[1], 2) # vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78: