• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# A wrapper around the (optional) built-in class dbm, supporting keys
2# and values of almost any type instead of just string.
3# (Actually, this works only for keys and values that can be read back
4# correctly after being converted to a string.)
5
6
7class Dbm:
8
9    def __init__(self, filename, mode, perm):
10        import dbm
11        self.db = dbm.open(filename, mode, perm)
12
13    def __repr__(self):
14        s = ''
15        for key in self.keys():
16            t = repr(key) + ': ' + repr(self[key])
17            if s: t = ', ' + t
18            s = s + t
19        return '{' + s + '}'
20
21    def __len__(self):
22        return len(self.db)
23
24    def __getitem__(self, key):
25        return eval(self.db[repr(key)])
26
27    def __setitem__(self, key, value):
28        self.db[repr(key)] = repr(value)
29
30    def __delitem__(self, key):
31        del self.db[repr(key)]
32
33    def keys(self):
34        res = []
35        for key in self.db.keys():
36            res.append(eval(key))
37        return res
38
39    def has_key(self, key):
40        return self.db.has_key(repr(key))
41
42
43def test():
44    d = Dbm('@dbm', 'rw', 0600)
45    print d
46    while 1:
47        try:
48            key = input('key: ')
49            if d.has_key(key):
50                value = d[key]
51                print 'currently:', value
52            value = input('value: ')
53            if value is None:
54                del d[key]
55            else:
56                d[key] = value
57        except KeyboardInterrupt:
58            print ''
59            print d
60        except EOFError:
61            print '[eof]'
62            break
63    print d
64
65
66test()
67