blob: 8a34dd6f4ef6472dbb0314e475edd2ff120899ca [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001:mod:`shelve` --- Python object persistence
2===========================================
3
4.. module:: shelve
5 :synopsis: Python object persistence.
6
7
8.. index:: module: pickle
9
10A "shelf" is a persistent, dictionary-like object. The difference with "dbm"
11databases is that the values (not the keys!) in a shelf can be essentially
12arbitrary Python objects --- anything that the :mod:`pickle` module can handle.
13This includes most class instances, recursive data types, and objects containing
14lots of shared sub-objects. The keys are ordinary strings.
15
16
17.. function:: open(filename[, flag='c'[, protocol=None[, writeback=False]]])
18
19 Open a persistent dictionary. The filename specified is the base filename for
20 the underlying database. As a side-effect, an extension may be added to the
21 filename and more than one file may be created. By default, the underlying
22 database file is opened for reading and writing. The optional *flag* parameter
23 has the same interpretation as the *flag* parameter of :func:`anydbm.open`.
24
25 By default, version 0 pickles are used to serialize values. The version of the
26 pickle protocol can be specified with the *protocol* parameter.
27
28 .. versionchanged:: 2.3
29 The *protocol* parameter was added.
30
31 By default, mutations to persistent-dictionary mutable entries are not
32 automatically written back. If the optional *writeback* parameter is set to
33 *True*, all entries accessed are cached in memory, and written back at close
34 time; this can make it handier to mutate mutable entries in the persistent
35 dictionary, but, if many entries are accessed, it can consume vast amounts of
36 memory for the cache, and it can make the close operation very slow since all
37 accessed entries are written back (there is no way to determine which accessed
38 entries are mutable, nor which ones were actually mutated).
39
Georg Brandld8282ee2009-05-08 12:17:34 +000040Shelf objects support all methods supported by dictionaries. This eases the
Georg Brandl8ec7f652007-08-15 14:28:01 +000041transition from dictionary based scripts to those requiring persistent storage.
42
43One additional method is supported:
44
45
46.. method:: Shelf.sync()
47
48 Write back all entries in the cache if the shelf was opened with *writeback* set
49 to *True*. Also empty the cache and synchronize the persistent dictionary on
50 disk, if feasible. This is called automatically when the shelf is closed with
51 :meth:`close`.
52
Raymond Hettinger64906bb2009-04-04 05:37:47 +000053.. seealso::
54
55 `Persistent dictionary recipe <http://code.activestate.com/recipes/576642/>`_
56 with widely supported storage formats and having the speed of native
57 dictionaries.
58
Georg Brandl8ec7f652007-08-15 14:28:01 +000059
60Restrictions
61------------
62
63 .. index::
64 module: dbm
65 module: gdbm
66 module: bsddb
67
68* The choice of which database package will be used (such as :mod:`dbm`,
69 :mod:`gdbm` or :mod:`bsddb`) depends on which interface is available. Therefore
70 it is not safe to open the database directly using :mod:`dbm`. The database is
71 also (unfortunately) subject to the limitations of :mod:`dbm`, if it is used ---
72 this means that (the pickled representation of) the objects stored in the
73 database should be fairly small, and in rare cases key collisions may cause the
74 database to refuse updates.
75
76* Depending on the implementation, closing a persistent dictionary may or may
77 not be necessary to flush changes to disk. The :meth:`__del__` method of the
78 :class:`Shelf` class calls the :meth:`close` method, so the programmer generally
79 need not do this explicitly.
80
81* The :mod:`shelve` module does not support *concurrent* read/write access to
82 shelved objects. (Multiple simultaneous read accesses are safe.) When a
83 program has a shelf open for writing, no other program should have it open for
84 reading or writing. Unix file locking can be used to solve this, but this
85 differs across Unix versions and requires knowledge about the database
86 implementation used.
87
88
89.. class:: Shelf(dict[, protocol=None[, writeback=False]])
90
91 A subclass of :class:`UserDict.DictMixin` which stores pickled values in the
92 *dict* object.
93
94 By default, version 0 pickles are used to serialize values. The version of the
95 pickle protocol can be specified with the *protocol* parameter. See the
96 :mod:`pickle` documentation for a discussion of the pickle protocols.
97
98 .. versionchanged:: 2.3
99 The *protocol* parameter was added.
100
101 If the *writeback* parameter is ``True``, the object will hold a cache of all
102 entries accessed and write them back to the *dict* at sync and close times.
103 This allows natural operations on mutable entries, but can consume much more
104 memory and make sync and close take a long time.
105
106
107.. class:: BsdDbShelf(dict[, protocol=None[, writeback=False]])
108
109 A subclass of :class:`Shelf` which exposes :meth:`first`, :meth:`next`,
110 :meth:`previous`, :meth:`last` and :meth:`set_location` which are available in
111 the :mod:`bsddb` module but not in other database modules. The *dict* object
112 passed to the constructor must support those methods. This is generally
113 accomplished by calling one of :func:`bsddb.hashopen`, :func:`bsddb.btopen` or
114 :func:`bsddb.rnopen`. The optional *protocol* and *writeback* parameters have
115 the same interpretation as for the :class:`Shelf` class.
116
117
118.. class:: DbfilenameShelf(filename[, flag='c'[, protocol=None[, writeback=False]]])
119
120 A subclass of :class:`Shelf` which accepts a *filename* instead of a dict-like
121 object. The underlying file will be opened using :func:`anydbm.open`. By
122 default, the file will be created and opened for both read and write. The
123 optional *flag* parameter has the same interpretation as for the :func:`open`
124 function. The optional *protocol* and *writeback* parameters have the same
125 interpretation as for the :class:`Shelf` class.
126
127
128Example
129-------
130
131To summarize the interface (``key`` is a string, ``data`` is an arbitrary
132object)::
133
134 import shelve
135
136 d = shelve.open(filename) # open -- file may get suffix added by low-level
137 # library
138
139 d[key] = data # store data at key (overwrites old data if
140 # using an existing key)
141 data = d[key] # retrieve a COPY of data at key (raise KeyError if no
142 # such key)
143 del d[key] # delete data stored at key (raises KeyError
144 # if no such key)
145 flag = d.has_key(key) # true if the key exists
146 klist = d.keys() # a list of all existing keys (slow!)
147
148 # as d was opened WITHOUT writeback=True, beware:
149 d['xx'] = range(4) # this works as expected, but...
Georg Brandl75f11072009-04-05 10:32:26 +0000150 d['xx'].append(5) # *this doesn't!* -- d['xx'] is STILL range(4)!
Georg Brandl8ec7f652007-08-15 14:28:01 +0000151
152 # having opened d without writeback=True, you need to code carefully:
153 temp = d['xx'] # extracts the copy
154 temp.append(5) # mutates the copy
155 d['xx'] = temp # stores the copy right back, to persist it
156
157 # or, d=shelve.open(filename,writeback=True) would let you just code
158 # d['xx'].append(5) and have it work as expected, BUT it would also
159 # consume more memory and make the d.close() operation slower.
160
161 d.close() # close it
162
163
164.. seealso::
165
166 Module :mod:`anydbm`
167 Generic interface to ``dbm``\ -style databases.
168
169 Module :mod:`bsddb`
170 BSD ``db`` database interface.
171
172 Module :mod:`dbhash`
173 Thin layer around the :mod:`bsddb` which provides an :func:`open` function like
174 the other database modules.
175
176 Module :mod:`dbm`
177 Standard Unix database interface.
178
179 Module :mod:`dumbdbm`
180 Portable implementation of the ``dbm`` interface.
181
182 Module :mod:`gdbm`
183 GNU database interface, based on the ``dbm`` interface.
184
185 Module :mod:`pickle`
186 Object serialization used by :mod:`shelve`.
187
188 Module :mod:`cPickle`
189 High-performance version of :mod:`pickle`.
190