shelve — Python 对象持久性

源代码: Lib/shelve.py


A “shelf” is a persistent, dictionary-like object. The difference with “dbm” databases is that the values (not the keys!) in a shelf can be essentially arbitrary Python objects — anything that the pickle module can handle. This includes most class instances, recursive data types, and objects containing lots of shared sub-objects. The keys are ordinary strings.

shelve. open ( filename , flag = 'c' , protocol = None , writeback = False )

Open a persistent dictionary. The filename specified is the base filename for the underlying database. As a side-effect, an extension may be added to the filename and more than one file may be created. By default, the underlying database file is opened for reading and writing. The optional flag parameter has the same interpretation as the flag 参数对于 dbm.open() .

By default, pickles created with pickle.DEFAULT_PROTOCOL are used to serialize values. The version of the pickle protocol can be specified with the protocol 参数。

Because of Python semantics, a shelf cannot know when a mutable persistent-dictionary entry is modified. By default modified objects are written only when assigned to the shelf (see 范例 ). If the optional writeback parameter is set to True , all entries accessed are also cached in memory, and written back on sync() and close() ; this can make it handier to mutate mutable entries in the persistent dictionary, but, if many entries are accessed, it can consume vast amounts of memory for the cache, and it can make the close operation very slow since all accessed entries are written back (there is no way to determine which accessed entries are mutable, nor which ones were actually mutated).

3.10 版改变: pickle.DEFAULT_PROTOCOL is now used as the default pickle protocol.

3.11 版改变: 接受 像路径对象 for filename.