2
:mod:`shelve` --- Python object persistence
3
===========================================
6
:synopsis: Python object persistence.
9
.. index:: module: pickle
11
A "shelf" is a persistent, dictionary-like object. The difference with "dbm"
12
databases is that the values (not the keys!) in a shelf can be essentially
13
arbitrary Python objects --- anything that the :mod:`pickle` module can handle.
14
This includes most class instances, recursive data types, and objects containing
15
lots of shared sub-objects. The keys are ordinary strings.
18
.. function:: open(filename[, flag='c'[, protocol=None[, writeback=False]]])
20
Open a persistent dictionary. The filename specified is the base filename for
21
the underlying database. As a side-effect, an extension may be added to the
22
filename and more than one file may be created. By default, the underlying
23
database file is opened for reading and writing. The optional *flag* parameter
24
has the same interpretation as the *flag* parameter of :func:`dbm.open`.
26
By default, version 3 pickles are used to serialize values. The version of the
27
pickle protocol can be specified with the *protocol* parameter.
29
By default, mutations to persistent-dictionary mutable entries are not
30
automatically written back. If the optional *writeback* parameter is set to
31
*True*, all entries accessed are cached in memory, and written back at close
32
time; this can make it handier to mutate mutable entries in the persistent
33
dictionary, but, if many entries are accessed, it can consume vast amounts of
34
memory for the cache, and it can make the close operation very slow since all
35
accessed entries are written back (there is no way to determine which accessed
36
entries are mutable, nor which ones were actually mutated).
38
Shelve objects support all methods supported by dictionaries. This eases the
39
transition from dictionary based scripts to those requiring persistent storage.
41
One additional method is supported:
44
.. method:: Shelf.sync()
46
Write back all entries in the cache if the shelf was opened with *writeback* set
47
to *True*. Also empty the cache and synchronize the persistent dictionary on
48
disk, if feasible. This is called automatically when the shelf is closed with
59
* The choice of which database package will be used (such as :mod:`dbm.ndbm` or
60
:mod:`dbm.gnu`) depends on which interface is available. Therefore it is not
61
safe to open the database directly using :mod:`dbm`. The database is also
62
(unfortunately) subject to the limitations of :mod:`dbm`, if it is used ---
63
this means that (the pickled representation of) the objects stored in the
64
database should be fairly small, and in rare cases key collisions may cause
65
the database to refuse updates.
67
* Depending on the implementation, closing a persistent dictionary may or may
68
not be necessary to flush changes to disk. The :meth:`__del__` method of the
69
:class:`Shelf` class calls the :meth:`close` method, so the programmer generally
70
need not do this explicitly.
72
* The :mod:`shelve` module does not support *concurrent* read/write access to
73
shelved objects. (Multiple simultaneous read accesses are safe.) When a
74
program has a shelf open for writing, no other program should have it open for
75
reading or writing. Unix file locking can be used to solve this, but this
76
differs across Unix versions and requires knowledge about the database
80
.. class:: Shelf(dict[, protocol=None[, writeback=False]])
82
A subclass of :class:`collections.MutableMapping` which stores pickled values
85
By default, version 0 pickles are used to serialize values. The version of the
86
pickle protocol can be specified with the *protocol* parameter. See the
87
:mod:`pickle` documentation for a discussion of the pickle protocols.
89
If the *writeback* parameter is ``True``, the object will hold a cache of all
90
entries accessed and write them back to the *dict* at sync and close times.
91
This allows natural operations on mutable entries, but can consume much more
92
memory and make sync and close take a long time.
95
.. class:: BsdDbShelf(dict[, protocol=None[, writeback=False]])
97
A subclass of :class:`Shelf` which exposes :meth:`first`, :meth:`next`,
98
:meth:`previous`, :meth:`last` and :meth:`set_location` which are available in
99
the :mod:`bsddb` module but not in other database modules. The *dict* object
100
passed to the constructor must support those methods. This is generally
101
accomplished by calling one of :func:`bsddb.hashopen`, :func:`bsddb.btopen` or
102
:func:`bsddb.rnopen`. The optional *protocol* and *writeback* parameters have
103
the same interpretation as for the :class:`Shelf` class.
106
.. class:: DbfilenameShelf(filename[, flag='c'[, protocol=None[, writeback=False]]])
108
A subclass of :class:`Shelf` which accepts a *filename* instead of a dict-like
109
object. The underlying file will be opened using :func:`dbm.open`. By
110
default, the file will be created and opened for both read and write. The
111
optional *flag* parameter has the same interpretation as for the :func:`open`
112
function. The optional *protocol* and *writeback* parameters have the same
113
interpretation as for the :class:`Shelf` class.
119
To summarize the interface (``key`` is a string, ``data`` is an arbitrary
124
d = shelve.open(filename) # open -- file may get suffix added by low-level
127
d[key] = data # store data at key (overwrites old data if
128
# using an existing key)
129
data = d[key] # retrieve a COPY of data at key (raise KeyError if no
131
del d[key] # delete data stored at key (raises KeyError
133
flag = key in d # true if the key exists
134
klist = d.keys() # a list of all existing keys (slow!)
136
# as d was opened WITHOUT writeback=True, beware:
137
d['xx'] = range(4) # this works as expected, but...
138
d['xx'].append(5) # *this doesn't!* -- d['xx'] is STILL range(4)!!!
140
# having opened d without writeback=True, you need to code carefully:
141
temp = d['xx'] # extracts the copy
142
temp.append(5) # mutates the copy
143
d['xx'] = temp # stores the copy right back, to persist it
145
# or, d=shelve.open(filename,writeback=True) would let you just code
146
# d['xx'].append(5) and have it work as expected, BUT it would also
147
# consume more memory and make the d.close() operation slower.
155
Generic interface to ``dbm``-style databases.
158
Object serialization used by :mod:`shelve`.
160
Module :mod:`cPickle`
161
High-performance version of :mod:`pickle`.