blob: 2dee026ff34f6a2f455e72f735049913b45db0de [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
26 By default, version 0 pickles are used to serialize values. The version of the
27 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
51
52Restrictions
53------------
54
55 .. index::
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000056 module: dbm.ndbm
57 module: dbm.gnu
Georg Brandl116aa622007-08-15 14:28:22 +000058 module: bsddb
59
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000060* The choice of which database package will be used (such as :mod:`dbm.ndbm`,
61 :mod:`dbm.gnu` or :mod:`bsddb`) depends on which interface is available. Therefore
Georg Brandl116aa622007-08-15 14:28:22 +000062 it is not safe to open the database directly using :mod:`dbm`. The database is
63 also (unfortunately) subject to the limitations of :mod:`dbm`, if it is used ---
64 this means that (the pickled representation of) the objects stored in the
65 database should be fairly small, and in rare cases key collisions may cause the
66 database to refuse updates.
67
68* Depending on the implementation, closing a persistent dictionary may or may
69 not be necessary to flush changes to disk. The :meth:`__del__` method of the
70 :class:`Shelf` class calls the :meth:`close` method, so the programmer generally
71 need not do this explicitly.
72
73* The :mod:`shelve` module does not support *concurrent* read/write access to
74 shelved objects. (Multiple simultaneous read accesses are safe.) When a
75 program has a shelf open for writing, no other program should have it open for
76 reading or writing. Unix file locking can be used to solve this, but this
77 differs across Unix versions and requires knowledge about the database
78 implementation used.
79
80
81.. class:: Shelf(dict[, protocol=None[, writeback=False]])
82
Georg Brandlc7723722008-05-26 17:47:11 +000083 A subclass of :class:`collections.MutableMapping` which stores pickled values
84 in the *dict* object.
Georg Brandl116aa622007-08-15 14:28:22 +000085
86 By default, version 0 pickles are used to serialize values. The version of the
87 pickle protocol can be specified with the *protocol* parameter. See the
88 :mod:`pickle` documentation for a discussion of the pickle protocols.
89
Georg Brandl116aa622007-08-15 14:28:22 +000090 If the *writeback* parameter is ``True``, the object will hold a cache of all
91 entries accessed and write them back to the *dict* at sync and close times.
92 This allows natural operations on mutable entries, but can consume much more
93 memory and make sync and close take a long time.
94
95
96.. class:: BsdDbShelf(dict[, protocol=None[, writeback=False]])
97
98 A subclass of :class:`Shelf` which exposes :meth:`first`, :meth:`next`,
99 :meth:`previous`, :meth:`last` and :meth:`set_location` which are available in
100 the :mod:`bsddb` module but not in other database modules. The *dict* object
101 passed to the constructor must support those methods. This is generally
102 accomplished by calling one of :func:`bsddb.hashopen`, :func:`bsddb.btopen` or
103 :func:`bsddb.rnopen`. The optional *protocol* and *writeback* parameters have
104 the same interpretation as for the :class:`Shelf` class.
105
106
107.. class:: DbfilenameShelf(filename[, flag='c'[, protocol=None[, writeback=False]]])
108
109 A subclass of :class:`Shelf` which accepts a *filename* instead of a dict-like
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000110 object. The underlying file will be opened using :func:`dbm.open`. By
Georg Brandl116aa622007-08-15 14:28:22 +0000111 default, the file will be created and opened for both read and write. The
112 optional *flag* parameter has the same interpretation as for the :func:`open`
113 function. The optional *protocol* and *writeback* parameters have the same
114 interpretation as for the :class:`Shelf` class.
115
116
117Example
118-------
119
120To summarize the interface (``key`` is a string, ``data`` is an arbitrary
121object)::
122
123 import shelve
124
125 d = shelve.open(filename) # open -- file may get suffix added by low-level
126 # library
127
128 d[key] = data # store data at key (overwrites old data if
129 # using an existing key)
130 data = d[key] # retrieve a COPY of data at key (raise KeyError if no
131 # such key)
132 del d[key] # delete data stored at key (raises KeyError
133 # if no such key)
Collin Winterc79461b2007-09-01 23:34:30 +0000134 flag = key in d # true if the key exists
Georg Brandl116aa622007-08-15 14:28:22 +0000135 klist = d.keys() # a list of all existing keys (slow!)
136
137 # as d was opened WITHOUT writeback=True, beware:
138 d['xx'] = range(4) # this works as expected, but...
139 d['xx'].append(5) # *this doesn't!* -- d['xx'] is STILL range(4)!!!
140
141 # having opened d without writeback=True, you need to code carefully:
142 temp = d['xx'] # extracts the copy
143 temp.append(5) # mutates the copy
144 d['xx'] = temp # stores the copy right back, to persist it
145
146 # or, d=shelve.open(filename,writeback=True) would let you just code
147 # d['xx'].append(5) and have it work as expected, BUT it would also
148 # consume more memory and make the d.close() operation slower.
149
150 d.close() # close it
151
152
153.. seealso::
154
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000155 Module :mod:`dbm`
156 Generic interface to ``dbm``-style databases.
Georg Brandl116aa622007-08-15 14:28:22 +0000157
158 Module :mod:`bsddb`
159 BSD ``db`` database interface.
160
Georg Brandl116aa622007-08-15 14:28:22 +0000161 Module :mod:`pickle`
162 Object serialization used by :mod:`shelve`.
163
164 Module :mod:`cPickle`
165 High-performance version of :mod:`pickle`.
166