mirror of
https://github.com/Mikaela/Limnoria.git
synced 2024-11-23 19:19:32 +01:00
Added PersistentDictionary.
This commit is contained in:
parent
fa589ac423
commit
b9434a23a6
@ -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()
|
||||||
|
@ -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:
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user