Welcome, guest | Sign In | My Account | Store | Cart

A crude persistent dict class. Intended for saving GUI user preferences that can be hand edited, cf. shelve module. Probably not suitable for large amounts of data.

Python, 70 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""
A persistent dict object that uses a text file for storage.

Saved values will update arguments passed to constructor with:
PersistentTextDict(<path>, dict={'a':10}, foo='baz', bla=10)
This behavior allows setting defaults that can be overridden
in a text file on disk.

NOTE: str, int, float, list, dict et. el. support only.
"""
import UserDict

class PersistentTextDict(UserDict.UserDict):
    """
    >>> d = PersistentTextDict('test.dict')
    >>> d['username'] = 'jsmith'
    >>> del d
    >>> d1 = PersistentTextDict('test.dict')
    >>> d1['username']
    'jsmith'
    >>> d1['a'] = 10000
    >>> d1['a']
    10000
    >>> d2 = PersistentTextDict('test.dict')
    >>> d2['a']
    10000
    >>> del d2['a']
    >>> del d2
    >>> d3 = PersistentTextDict('test.dict')
    >>> d3.has_key('a')
    False
    >>> d3.update({'a':9999})
    >>> d3['a']
    9999
    """
    def __init__(self, path, dict=None, **kwargs):
        UserDict.UserDict.__init__(self)
        self.path = path
        try:
            self.isLoad = True
            if dict is not None:
                self.update(dict)
            if len(kwargs):
                self.update(kwargs)
            self.update(eval(open(path, 'r').read()))
            self.isLoad = False
        except IOError:
            self.isLoad = False

    def sync(self):
        import pprint
        open(self.path, 'w').write(pprint.pformat(self.data) + '\n')

    def __setitem__(self, key, item):
        self.data[key] = item
        self.sync()

    def __delitem__(self, key):
        del self.data[key]
        self.sync()

    def update(self, dict=None, **kwargs):
        UserDict.UserDict.update(self, dict=dict, **kwargs)
        if not self.isLoad:
            self.sync()


if __name__ == "__main__":
    import doctest
    doctest.testmod()