Added PersistentDictionary.

This commit is contained in:
Jeremy Fincher 2003-10-24 09:53:03 +00:00
parent fa589ac423
commit b9434a23a6
2 changed files with 41 additions and 0 deletions

View File

@ -38,6 +38,7 @@ Data structures for Python.
import fix import fix
import types import types
import string
class RingBuffer(object): class RingBuffer(object):
"""Class to represent a fixed-size ring buffer.""" """Class to represent a fixed-size ring buffer."""
@ -340,3 +341,30 @@ class TwoWayDictionary(dict):
value = self[key] value = self[key]
dict.__delitem__(self, key) dict.__delitem__(self, key)
dict.__delitem__(self, value) 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()

View File

@ -576,5 +576,18 @@ class TwoWayDictionaryTestCase(unittest.TestCase):
self.failIf('foo' 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: # vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78: