blob: 8121004f56dd04e87a7278b9d4a3bf7d09e8d7ee [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`shelve` --- Python object persistence
3===========================================
4
5.. module:: shelve
6 :synopsis: Python object persistence.
7
8
9.. index:: module: pickle
10
11A "shelf" is a persistent, dictionary-like object. The difference with "dbm"
12databases is that the values (not the keys!) in a shelf can be essentially
13arbitrary Python objects --- anything that the :mod:`pickle` module can handle.
14This includes most class instances, recursive data types, and objects containing
15lots of shared sub-objects. The keys are ordinary strings.
16
17
18.. function:: open(filename[, flag='c'[, protocol=None[, writeback=False]]])
19
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
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000024 has the same interpretation as the *flag* parameter of :func:`dbm.open`.
Georg Brandl116aa622007-08-15 14:28:22 +000025
Raymond Hettinger85602262009-02-03 04:19:10 +000026 By default, version 3 pickles are used to serialize values. The version of the
Georg Brandl116aa622007-08-15 14:28:22 +000027 pickle protocol can be specified with the *protocol* parameter.
28
Georg Brandl116aa622007-08-15 14:28:22 +000029 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).
37
38Shelve objects support all methods supported by dictionaries. This eases the
39transition from dictionary based scripts to those requiring persistent storage.
40
41One additional method is supported:
42
43
44.. method:: Shelf.sync()
45
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
49 :meth:`close`.
50
Raymond Hettinger65c9eb22009-04-04 05:39:52 +000051.. seealso::
52
53 `Persistent dictionary recipe <http://code.activestate.com/recipes/576642/>`_
54 with widely supported storage formats and having the speed of native
55 dictionaries.
56
Georg Brandl116aa622007-08-15 14:28:22 +000057
58Restrictions
59------------
60
61 .. index::
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000062 module: dbm.ndbm
63 module: dbm.gnu
Georg Brandl116aa622007-08-15 14:28:22 +000064
Benjamin Peterson9a46cab2008-09-08 02:49:30 +000065* The choice of which database package will be used (such as :mod:`dbm.ndbm` or
66 :mod:`dbm.gnu`) depends on which interface is available. Therefore it is not
67 safe to open the database directly using :mod:`dbm`. The database is also
68 (unfortunately) subject to the limitations of :mod:`dbm`, if it is used ---
Georg Brandl116aa622007-08-15 14:28:22 +000069 this means that (the pickled representation of) the objects stored in the
Benjamin Peterson9a46cab2008-09-08 02:49:30 +000070 database should be fairly small, and in rare cases key collisions may cause
71 the database to refuse updates.
Georg Brandl116aa622007-08-15 14:28:22 +000072
73* Depending on the implementation, closing a persistent dictionary may or may
74 not be necessary to flush changes to disk. The :meth:`__del__` method of the
75 :class:`Shelf` class calls the :meth:`close` method, so the programmer generally
76 need not do this explicitly.
77
78* The :mod:`shelve` module does not support *concurrent* read/write access to
79 shelved objects. (Multiple simultaneous read accesses are safe.) When a
80 program has a shelf open for writing, no other program should have it open for
81 reading or writing. Unix file locking can be used to solve this, but this
82 differs across Unix versions and requires knowledge about the database
83 implementation used.
84
85
86.. class:: Shelf(dict[, protocol=None[, writeback=False]])
87
Georg Brandlc7723722008-05-26 17:47:11 +000088 A subclass of :class:`collections.MutableMapping` which stores pickled values
89 in the *dict* object.
Georg Brandl116aa622007-08-15 14:28:22 +000090
91 By default, version 0 pickles are used to serialize values. The version of the
92 pickle protocol can be specified with the *protocol* parameter. See the
93 :mod:`pickle` documentation for a discussion of the pickle protocols.
94
Georg Brandl116aa622007-08-15 14:28:22 +000095 If the *writeback* parameter is ``True``, the object will hold a cache of all
96 entries accessed and write them back to the *dict* at sync and close times.
97 This allows natural operations on mutable entries, but can consume much more
98 memory and make sync and close take a long time.
99
100
101.. class:: BsdDbShelf(dict[, protocol=None[, writeback=False]])
102
103 A subclass of :class:`Shelf` which exposes :meth:`first`, :meth:`next`,
104 :meth:`previous`, :meth:`last` and :meth:`set_location` which are available in
105 the :mod:`bsddb` module but not in other database modules. The *dict* object
106 passed to the constructor must support those methods. This is generally
107 accomplished by calling one of :func:`bsddb.hashopen`, :func:`bsddb.btopen` or
108 :func:`bsddb.rnopen`. The optional *protocol* and *writeback* parameters have
109 the same interpretation as for the :class:`Shelf` class.
110
111
112.. class:: DbfilenameShelf(filename[, flag='c'[, protocol=None[, writeback=False]]])
113
114 A subclass of :class:`Shelf` which accepts a *filename* instead of a dict-like
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000115 object. The underlying file will be opened using :func:`dbm.open`. By
Georg Brandl116aa622007-08-15 14:28:22 +0000116 default, the file will be created and opened for both read and write. The
117 optional *flag* parameter has the same interpretation as for the :func:`open`
118 function. The optional *protocol* and *writeback* parameters have the same
119 interpretation as for the :class:`Shelf` class.
120
121
122Example
123-------
124
125To summarize the interface (``key`` is a string, ``data`` is an arbitrary
126object)::
127
128 import shelve
129
130 d = shelve.open(filename) # open -- file may get suffix added by low-level
131 # library
132
133 d[key] = data # store data at key (overwrites old data if
134 # using an existing key)
135 data = d[key] # retrieve a COPY of data at key (raise KeyError if no
136 # such key)
137 del d[key] # delete data stored at key (raises KeyError
138 # if no such key)
Collin Winterc79461b2007-09-01 23:34:30 +0000139 flag = key in d # true if the key exists
Georg Brandl116aa622007-08-15 14:28:22 +0000140 klist = d.keys() # a list of all existing keys (slow!)
141
142 # as d was opened WITHOUT writeback=True, beware:
143 d['xx'] = range(4) # this works as expected, but...
Benjamin Petersond23f8222009-04-05 19:13:16 +0000144 d['xx'].append(5) # *this doesn't!* -- d['xx'] is STILL range(4)!
Georg Brandl116aa622007-08-15 14:28:22 +0000145
146 # having opened d without writeback=True, you need to code carefully:
147 temp = d['xx'] # extracts the copy
148 temp.append(5) # mutates the copy
149 d['xx'] = temp # stores the copy right back, to persist it
150
151 # or, d=shelve.open(filename,writeback=True) would let you just code
152 # d['xx'].append(5) and have it work as expected, BUT it would also
153 # consume more memory and make the d.close() operation slower.
154
155 d.close() # close it
156
157
158.. seealso::
159
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000160 Module :mod:`dbm`
161 Generic interface to ``dbm``-style databases.
Georg Brandl116aa622007-08-15 14:28:22 +0000162
Georg Brandl116aa622007-08-15 14:28:22 +0000163 Module :mod:`pickle`
164 Object serialization used by :mod:`shelve`.
165
166 Module :mod:`cPickle`
167 High-performance version of :mod:`pickle`.
168