1992-08-13 09:14:11 -03:00
|
|
|
# A wrapper around the (optional) built-in class dbm, supporting keys
|
|
|
|
# and values of almost any type instead of just string.
|
|
|
|
# (Actually, this works only for keys and values that can be read back
|
|
|
|
# correctly after being converted to a string.)
|
|
|
|
|
|
|
|
|
|
|
|
class Dbm:
|
|
|
|
|
2003-04-24 14:13:18 -03:00
|
|
|
def __init__(self, filename, mode, perm):
|
|
|
|
import dbm
|
|
|
|
self.db = dbm.open(filename, mode, perm)
|
1992-08-13 09:14:11 -03:00
|
|
|
|
2003-04-24 14:13:18 -03:00
|
|
|
def __repr__(self):
|
|
|
|
s = ''
|
|
|
|
for key in self.keys():
|
|
|
|
t = `key` + ': ' + `self[key]`
|
|
|
|
if s: t = ', ' + t
|
|
|
|
s = s + t
|
|
|
|
return '{' + s + '}'
|
1992-08-13 09:14:11 -03:00
|
|
|
|
2003-04-24 14:13:18 -03:00
|
|
|
def __len__(self):
|
|
|
|
return len(self.db)
|
1992-08-13 09:14:11 -03:00
|
|
|
|
2003-04-24 14:13:18 -03:00
|
|
|
def __getitem__(self, key):
|
|
|
|
return eval(self.db[`key`])
|
1992-08-13 09:14:11 -03:00
|
|
|
|
2003-04-24 14:13:18 -03:00
|
|
|
def __setitem__(self, key, value):
|
|
|
|
self.db[`key`] = `value`
|
1992-08-13 09:14:11 -03:00
|
|
|
|
2003-04-24 14:13:18 -03:00
|
|
|
def __delitem__(self, key):
|
|
|
|
del self.db[`key`]
|
1992-08-13 09:14:11 -03:00
|
|
|
|
2003-04-24 14:13:18 -03:00
|
|
|
def keys(self):
|
|
|
|
res = []
|
|
|
|
for key in self.db.keys():
|
|
|
|
res.append(eval(key))
|
|
|
|
return res
|
1992-08-13 09:14:11 -03:00
|
|
|
|
2003-04-24 14:13:18 -03:00
|
|
|
def has_key(self, key):
|
|
|
|
return self.db.has_key(`key`)
|
1992-08-13 09:14:11 -03:00
|
|
|
|
|
|
|
|
|
|
|
def test():
|
2003-04-24 14:13:18 -03:00
|
|
|
d = Dbm('@dbm', 'rw', 0600)
|
|
|
|
print d
|
|
|
|
while 1:
|
|
|
|
try:
|
|
|
|
key = input('key: ')
|
|
|
|
if d.has_key(key):
|
|
|
|
value = d[key]
|
|
|
|
print 'currently:', value
|
|
|
|
value = input('value: ')
|
|
|
|
if value == None:
|
|
|
|
del d[key]
|
|
|
|
else:
|
|
|
|
d[key] = value
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
print ''
|
|
|
|
print d
|
|
|
|
except EOFError:
|
|
|
|
print '[eof]'
|
|
|
|
break
|
|
|
|
print d
|
1992-08-13 09:14:11 -03:00
|
|
|
|
|
|
|
|
|
|
|
test()
|