Issue #1523: Remove deprecated overflow masking in struct module, and
[python.git] / Demo / classes / Dbm.py
blob892c103e0cf607451099f09754b65c2a17924e5e
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.)
7 class Dbm:
9 def __init__(self, filename, mode, perm):
10 import dbm
11 self.db = dbm.open(filename, mode, perm)
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 + '}'
21 def __len__(self):
22 return len(self.db)
24 def __getitem__(self, key):
25 return eval(self.db[repr(key)])
27 def __setitem__(self, key, value):
28 self.db[repr(key)] = repr(value)
30 def __delitem__(self, key):
31 del self.db[repr(key)]
33 def keys(self):
34 res = []
35 for key in self.db.keys():
36 res.append(eval(key))
37 return res
39 def has_key(self, key):
40 return self.db.has_key(repr(key))
43 def 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
66 test()