blob: 8fccb6a2f4ad12376514b28b253533e42cdb67a1 [file] [log] [blame]
Guido van Rossume8769491992-08-13 12:14:11 +00001# 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
7def opendbm(filename, mode, perm):
8 return Dbm().init(filename, mode, perm)
9
10
11class Dbm:
12
13 def init(self, filename, mode, perm):
14 import dbm
15 self.db = dbm.open(filename, mode, perm)
16 return self
17
18 def __repr__(self):
19 s = ''
20 for key in self.keys():
21 t = `key` + ': ' + `self[key]`
22 if s: t = t + ', '
23 s = s + t
24 return '{' + s + '}'
25
26 def __len__(self):
27 return len(self.db)
28
29 def __getitem__(self, key):
30 return eval(self.db[`key`])
31
32 def __setitem__(self, key, value):
33 self.db[`key`] = `value`
34
35 def __delitem__(self, key):
36 del self.db[`key`]
37
38 def keys(self):
39 res = []
40 for key in self.db.keys():
41 res.append(eval(key))
42 return res
43
44 def has_key(self, key):
45 return self.db.has_key(`key`)
46
47
48def test():
49 d = opendbm('@dbm', 'rw', 0666)
50 print d
51 while 1:
52 try:
53 key = eval(raw_input('key: '))
54 if d.has_key(key):
55 value = d[key]
56 print 'currently:', value
57 value = eval(raw_input('value: '))
58 if value == None:
59 del d[key]
60 else:
61 d[key] = value
62 except KeyboardInterrupt:
63 print ''
64 print d
65 except EOFError:
66 print '[eof]'
67 break
68 print d
69
70
71test()