0
0
mirror of https://github.com/python/cpython.git synced 2024-11-28 16:45:42 +01:00
cpython/Demo/classes/Dbm.py

67 lines
1.2 KiB
Python
Raw Normal View History

1992-08-13 14:14:11 +02: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:
1993-10-30 13:38:16 +01:00
def __init__(self, filename, mode, perm):
1992-08-13 14:14:11 +02:00
import dbm
self.db = dbm.open(filename, mode, perm)
def __repr__(self):
s = ''
for key in self.keys():
t = `key` + ': ' + `self[key]`
1993-10-30 13:38:16 +01:00
if s: t = ', ' + t
1992-08-13 14:14:11 +02:00
s = s + t
return '{' + s + '}'
def __len__(self):
return len(self.db)
def __getitem__(self, key):
return eval(self.db[`key`])
def __setitem__(self, key, value):
self.db[`key`] = `value`
def __delitem__(self, key):
del self.db[`key`]
def keys(self):
res = []
for key in self.db.keys():
res.append(eval(key))
return res
def has_key(self, key):
return self.db.has_key(`key`)
def test():
1993-12-17 15:23:52 +01:00
d = Dbm('@dbm', 'rw', 0600)
1992-08-13 14:14:11 +02:00
print d
while 1:
try:
1993-12-17 15:23:52 +01:00
key = input('key: ')
1992-08-13 14:14:11 +02:00
if d.has_key(key):
value = d[key]
print 'currently:', value
1993-10-30 13:38:16 +01:00
value = input('value: ')
1992-08-13 14:14:11 +02:00
if value == None:
del d[key]
else:
d[key] = value
except KeyboardInterrupt:
print ''
print d
except EOFError:
print '[eof]'
break
print d
test()