这在文档中有所介绍。基本上,关键字参数writeback
toshelve.open
负责:
如果可选writeback
参数设置为True
,则所有访问的条目也都缓存在内存中,并写回sync()
and
close()
;这可以更方便地改变持久字典中的可变条目,但是,如果访问了许多条目,它会消耗大量内存用于缓存,并且由于所有访问的条目都被写回,它会使关闭操作非常慢(无法确定哪些访问的条目是可变的,也无法确定哪些条目实际上是突变的)。
来自同一页面的示例:
d = shelve.open(filename) # open -- file may get suffix added by low-level
# library
# as d was opened WITHOUT writeback=True, beware:
d['xx'] = range(4) # this works as expected, but...
d['xx'].append(5) # *this doesn't!* -- d['xx'] is STILL range(4)!
# having opened d without writeback=True, you need to code carefully:
temp = d['xx'] # extracts the copy
temp.append(5) # mutates the copy
d['xx'] = temp # stores the copy right back, to persist it
# or, d=shelve.open(filename,writeback=True) would let you just code
# d['xx'].append(5) and have it work as expected, BUT it would also
# consume more memory and make the d.close() operation slower.
d.close() # close it