blob: 5566f999adee04ca41b1b384f74f7de8a9259727 [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
Guido van Rossume8769491992-08-13 12:14:11 +00007class Dbm:
8
Andrew M. Kuchling946c53e2003-04-24 17:13:18 +00009 def __init__(self, filename, mode, perm):
10 import dbm
11 self.db = dbm.open(filename, mode, perm)
Guido van Rossume8769491992-08-13 12:14:11 +000012
Andrew M. Kuchling946c53e2003-04-24 17:13:18 +000013 def __repr__(self):
14 s = ''
15 for key in self.keys():
16 t = `key` + ': ' + `self[key]`
17 if s: t = ', ' + t
18 s = s + t
19 return '{' + s + '}'
Guido van Rossume8769491992-08-13 12:14:11 +000020
Andrew M. Kuchling946c53e2003-04-24 17:13:18 +000021 def __len__(self):
22 return len(self.db)
Guido van Rossume8769491992-08-13 12:14:11 +000023
Andrew M. Kuchling946c53e2003-04-24 17:13:18 +000024 def __getitem__(self, key):
25 return eval(self.db[`key`])
Guido van Rossume8769491992-08-13 12:14:11 +000026
Andrew M. Kuchling946c53e2003-04-24 17:13:18 +000027 def __setitem__(self, key, value):
28 self.db[`key`] = `value`
Guido van Rossume8769491992-08-13 12:14:11 +000029
Andrew M. Kuchling946c53e2003-04-24 17:13:18 +000030 def __delitem__(self, key):
31 del self.db[`key`]
Guido van Rossume8769491992-08-13 12:14:11 +000032
Andrew M. Kuchling946c53e2003-04-24 17:13:18 +000033 def keys(self):
34 res = []
35 for key in self.db.keys():
36 res.append(eval(key))
37 return res
Guido van Rossume8769491992-08-13 12:14:11 +000038
Andrew M. Kuchling946c53e2003-04-24 17:13:18 +000039 def has_key(self, key):
40 return self.db.has_key(`key`)
Guido van Rossume8769491992-08-13 12:14:11 +000041
42
43def test():
Andrew M. Kuchling946c53e2003-04-24 17:13:18 +000044 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 == 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
Guido van Rossume8769491992-08-13 12:14:11 +000064
65
66test()