这就是我所做的,尝试为类似 dict 的数据库创建一个包装器,以及其他功能:
class database(object):
def __init__(self, name):
self.name = name
self.db = anydbm.open(name, 'c')
def __getitem__(self, key):
key = str(key)
try:
self.db = anydbm.open(self.name, 'w')
except Exception,e:
raise e
else:
return cPickle.loads(self.db[key])
finally:
self.db.close()
def __setitem__(self, key, value):
key = str(key)
value = cPickle.dumps(value)
try:
self.db = anydbm.open(self.name, 'w')
except Exception,e:
print e
else:
self.db[key] = value
finally:
self.db.close()
当我尝试在嵌套的 dict 中定义新键时,似乎 getitem 返回的是值而不是引用,因此在 setitem 之后最终没有修改定义。
>>> from database import database
>>> db = database('test')
>>> db['a'] = {'alpha':'aaa'}
>>> db['a']['alpha'] = 'bbb'
>>> print db
{'a': {'alpha': 'aaa'}} //The value is not modified