blob: 84edbbec787ffc592a05b4bd242988aa77344199 [file] [log] [blame]
Georg Brandl0a7ac7d2008-05-26 10:29:35 +00001:mod:`dbm` --- Interfaces to Unix "databases"
2=============================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
4.. module:: dbm
Georg Brandl0a7ac7d2008-05-26 10:29:35 +00005 :synopsis: Interfaces to various Unix "database" formats.
6
7:mod:`dbm` is a generic interface to variants of the DBM database ---
Benjamin Peterson905aa662008-09-08 21:35:37 +00008 :mod:`dbm.gnu` or :mod:`dbm.ndbm`. If none of these modules is installed, the
9 slow-but-simple implementation in module :mod:`dbm.dumb` will be used. There
10 is a `third party interface <http://www.jcea.es/programacion/pybsddb.htm>`_ to
11 the Oracle Berkely DB.
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000012
13
14.. exception:: error
15
16 A tuple containing the exceptions that can be raised by each of the supported
17 modules, with a unique exception also named :exc:`dbm.error` as the first
18 item --- the latter is used when :exc:`dbm.error` is raised.
19
20
21.. function:: whichdb(filename)
22
23 This functionattempts to guess which of the several simple database modules
24 available --- :mod:`dbm.bsd`, :mod:`dbm.gnu`, :mod:`dbm.ndbm` or
25 :mod:`dbm.dumb` --- should be used to open a given file.
26
27 Returns one of the following values: ``None`` if the file can't be opened
28 because it's unreadable or doesn't exist; the empty string (``''``) if the
29 file's format can't be guessed; or a string containing the required module
30 name, such as ``'dbm.ndbm'`` or ``'dbm.gnu'``.
31
32
33.. function:: open(filename[, flag[, mode]])
34
35 Open the database file *filename* and return a corresponding object.
36
37 If the database file already exists, the :func:`whichdb` function is used to
38 determine its type and the appropriate module is used; if it does not exist,
39 the first module listed above that can be imported is used.
40
41 The optional *flag* argument can be ``'r'`` to open an existing database for
42 reading only, ``'w'`` to open an existing database for reading and writing,
43 ``'c'`` to create the database if it doesn't exist, or ``'n'``, which will
44 always create a new empty database. If not specified, the default value is
45 ``'r'``.
46
47 The optional *mode* argument is the Unix mode of the file, used only when the
48 database has to be created. It defaults to octal ``0o666`` (and will be
49 modified by the prevailing umask).
50
51
52The object returned by :func:`open` supports most of the same functionality as
53dictionaries; keys and their corresponding values can be stored, retrieved, and
54deleted, and the :keyword:`in` operator and the :meth:`keys` method are
Brett Cannon7317c1e2008-11-25 19:19:17 +000055available. Key and values are always stored as bytes. This means that when
56strings are used they are implicitly converted to the default encoding before
57being stored.
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000058
59The following example records some hostnames and a corresponding title, and
60then prints out the contents of the database::
61
62 import dbm
63
64 # Open database, creating it if necessary.
65 db = dbm.open('cache', 'c')
66
67 # Record some values
Brett Cannon7317c1e2008-11-25 19:19:17 +000068 db[b'hello'] = b'there'
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000069 db['www.python.org'] = 'Python Website'
70 db['www.cnn.com'] = 'Cable News Network'
71
Brett Cannon7317c1e2008-11-25 19:19:17 +000072 # Note that the keys are considered bytes now.
73 assert db[b'www.python.org'] == b'Python Website'
74 # Notice how the value is now in bytes.
75 assert db['www.cnn.com'] == b'Cable News Network'
76
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000077 # Loop through contents. Other dictionary methods
78 # such as .keys(), .values() also work.
79 for k, v in db.iteritems():
80 print(k, '\t', v)
81
82 # Storing a non-string key or value will raise an exception (most
83 # likely a TypeError).
84 db['www.yahoo.com'] = 4
85
86 # Close when done.
87 db.close()
88
89
90.. seealso::
91
92 Module :mod:`shelve`
93 Persistence module which stores non-string data.
94
95
96The individual submodules are described in the following sections.
97
98
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000099:mod:`dbm.gnu` --- GNU's reinterpretation of dbm
100------------------------------------------------
101
102.. module:: dbm.gnu
103 :platform: Unix
104 :synopsis: GNU's reinterpretation of dbm.
105
106
107This module is quite similar to the :mod:`dbm` module, but uses the GNU library
108``gdbm`` instead to provide some additional functionality. Please note that the
Brett Cannon7317c1e2008-11-25 19:19:17 +0000109file formats created by :mod:`dbm.gnu` and :mod:`dbm.ndbm` are incompatible.
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000110
111The :mod:`dbm.gnu` module provides an interface to the GNU DBM library.
Brett Cannon7317c1e2008-11-25 19:19:17 +0000112``dbm.gnu.gdbm`` objects behave like mappings (dictionaries), except that keys and
113values are always converted to bytes before storing. Printing a ``gdbm``
114object doesn't print the
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000115keys and values, and the :meth:`items` and :meth:`values` methods are not
116supported.
117
118.. exception:: error
119
Brett Cannon7317c1e2008-11-25 19:19:17 +0000120 Raised on :mod:`dbm.gnu`-specific errors, such as I/O errors. :exc:`KeyError` is
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000121 raised for general mapping errors like specifying an incorrect key.
122
123
124.. function:: open(filename, [flag, [mode]])
125
126 Open a ``gdbm`` database and return a :class:`gdbm` object. The *filename*
127 argument is the name of the database file.
128
129 The optional *flag* argument can be:
130
131 +---------+-------------------------------------------+
132 | Value | Meaning |
133 +=========+===========================================+
134 | ``'r'`` | Open existing database for reading only |
135 | | (default) |
136 +---------+-------------------------------------------+
137 | ``'w'`` | Open existing database for reading and |
138 | | writing |
139 +---------+-------------------------------------------+
140 | ``'c'`` | Open database for reading and writing, |
141 | | creating it if it doesn't exist |
142 +---------+-------------------------------------------+
143 | ``'n'`` | Always create a new, empty database, open |
144 | | for reading and writing |
145 +---------+-------------------------------------------+
146
147 The following additional characters may be appended to the flag to control
148 how the database is opened:
149
150 +---------+--------------------------------------------+
151 | Value | Meaning |
152 +=========+============================================+
153 | ``'f'`` | Open the database in fast mode. Writes |
154 | | to the database will not be synchronized. |
155 +---------+--------------------------------------------+
156 | ``'s'`` | Synchronized mode. This will cause changes |
157 | | to the database to be immediately written |
158 | | to the file. |
159 +---------+--------------------------------------------+
160 | ``'u'`` | Do not lock database. |
161 +---------+--------------------------------------------+
162
163 Not all flags are valid for all versions of ``gdbm``. The module constant
164 :const:`open_flags` is a string of supported flag characters. The exception
165 :exc:`error` is raised if an invalid flag is specified.
166
167 The optional *mode* argument is the Unix mode of the file, used only when the
Georg Brandlf4a41232008-05-26 17:55:52 +0000168 database has to be created. It defaults to octal ``0o666``.
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000169
170 In addition to the dictionary-like methods, ``gdbm`` objects have the
171 following methods:
172
173 .. method:: gdbm.firstkey()
174
175 It's possible to loop over every key in the database using this method and the
176 :meth:`nextkey` method. The traversal is ordered by ``gdbm``'s internal
177 hash values, and won't be sorted by the key values. This method returns
178 the starting key.
179
180 .. method:: gdbm.nextkey(key)
181
182 Returns the key that follows *key* in the traversal. The following code prints
183 every key in the database ``db``, without having to create a list in memory that
184 contains them all::
185
186 k = db.firstkey()
187 while k != None:
188 print(k)
189 k = db.nextkey(k)
190
191 .. method:: gdbm.reorganize()
192
193 If you have carried out a lot of deletions and would like to shrink the space
194 used by the ``gdbm`` file, this routine will reorganize the database. ``gdbm``
Brett Cannon7317c1e2008-11-25 19:19:17 +0000195 objects will not shorten the length of a database file except by using this
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000196 reorganization; otherwise, deleted file space will be kept and reused as new
197 (key, value) pairs are added.
198
199 .. method:: gdbm.sync()
200
201 When the database has been opened in fast mode, this method forces any
202 unwritten data to be written to the disk.
203
204
205:mod:`dbm.ndbm` --- Interface based on ndbm
206-------------------------------------------
207
208.. module:: dbm.ndbm
Georg Brandl116aa622007-08-15 14:28:22 +0000209 :platform: Unix
210 :synopsis: The standard "database" interface, based on ndbm.
211
212
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000213The :mod:`dbm.ndbm` module provides an interface to the Unix "(n)dbm" library.
214Dbm objects behave like mappings (dictionaries), except that keys and values are
Brett Cannon7317c1e2008-11-25 19:19:17 +0000215always stored as bytes. Printing a ``dbm`` object doesn't print the keys and
216values, and the :meth:`items` and :meth:`values` methods are not supported.
Georg Brandl116aa622007-08-15 14:28:22 +0000217
218This module can be used with the "classic" ndbm interface, the BSD DB
219compatibility interface, or the GNU GDBM compatibility interface. On Unix, the
220:program:`configure` script will attempt to locate the appropriate header file
221to simplify building this module.
222
Georg Brandl116aa622007-08-15 14:28:22 +0000223.. exception:: error
224
Brett Cannon7317c1e2008-11-25 19:19:17 +0000225 Raised on :mod:`dbm.ndbm`-specific errors, such as I/O errors. :exc:`KeyError` is raised
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000226 for general mapping errors like specifying an incorrect key.
Georg Brandl116aa622007-08-15 14:28:22 +0000227
228
229.. data:: library
230
231 Name of the ``ndbm`` implementation library used.
232
233
234.. function:: open(filename[, flag[, mode]])
235
Brett Cannon7317c1e2008-11-25 19:19:17 +0000236 Open a dbm database and return a ``dbm`` object. The *filename* argument is the
Georg Brandl116aa622007-08-15 14:28:22 +0000237 name of the database file (without the :file:`.dir` or :file:`.pag` extensions;
238 note that the BSD DB implementation of the interface will append the extension
239 :file:`.db` and only create one file).
240
241 The optional *flag* argument must be one of these values:
242
243 +---------+-------------------------------------------+
244 | Value | Meaning |
245 +=========+===========================================+
246 | ``'r'`` | Open existing database for reading only |
247 | | (default) |
248 +---------+-------------------------------------------+
249 | ``'w'`` | Open existing database for reading and |
250 | | writing |
251 +---------+-------------------------------------------+
252 | ``'c'`` | Open database for reading and writing, |
253 | | creating it if it doesn't exist |
254 +---------+-------------------------------------------+
255 | ``'n'`` | Always create a new, empty database, open |
256 | | for reading and writing |
257 +---------+-------------------------------------------+
258
259 The optional *mode* argument is the Unix mode of the file, used only when the
Georg Brandlf4a41232008-05-26 17:55:52 +0000260 database has to be created. It defaults to octal ``0o666`` (and will be
Georg Brandl116aa622007-08-15 14:28:22 +0000261 modified by the prevailing umask).
262
263
Georg Brandl116aa622007-08-15 14:28:22 +0000264
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000265:mod:`dbm.dumb` --- Portable DBM implementation
266-----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000267
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000268.. module:: dbm.dumb
269 :synopsis: Portable implementation of the simple DBM interface.
Georg Brandl116aa622007-08-15 14:28:22 +0000270
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000271.. index:: single: databases
Georg Brandl116aa622007-08-15 14:28:22 +0000272
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000273.. note::
274
275 The :mod:`dbm.dumb` module is intended as a last resort fallback for the
Brett Cannon7317c1e2008-11-25 19:19:17 +0000276 :mod:`dbm` module when a more robust module is not available. The :mod:`dbm.dumb`
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000277 module is not written for speed and is not nearly as heavily used as the other
278 database modules.
279
280The :mod:`dbm.dumb` module provides a persistent dictionary-like interface which
Brett Cannon7317c1e2008-11-25 19:19:17 +0000281is written entirely in Python. Unlike other modules such as :mod:`dbm.gnu` no
Benjamin Peterson9a46cab2008-09-08 02:49:30 +0000282external library is required. As with other persistent mappings, the keys and
Brett Cannon7317c1e2008-11-25 19:19:17 +0000283values are always stored as bytes.
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000284
285The module defines the following:
286
287
288.. exception:: error
289
Brett Cannon7317c1e2008-11-25 19:19:17 +0000290 Raised on :mod:`dbm.dumb`-specific errors, such as I/O errors. :exc:`KeyError` is
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000291 raised for general mapping errors like specifying an incorrect key.
292
293
294.. function:: open(filename[, flag[, mode]])
295
Brett Cannon7317c1e2008-11-25 19:19:17 +0000296 Open a ``dumbdbm`` database and return a dumbdbm object. The *filename* argument is
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000297 the basename of the database file (without any specific extensions). When a
298 dumbdbm database is created, files with :file:`.dat` and :file:`.dir` extensions
299 are created.
300
301 The optional *flag* argument is currently ignored; the database is always opened
302 for update, and will be created if it does not exist.
303
304 The optional *mode* argument is the Unix mode of the file, used only when the
305 database has to be created. It defaults to octal ``0o666`` (and will be modified
306 by the prevailing umask).
307
308 In addition to the methods provided by the :class:`collections.MutableMapping` class,
309 :class:`dumbdbm` objects provide the following method:
310
311 .. method:: dumbdbm.sync()
312
313 Synchronize the on-disk directory and data files. This method is called
314 by the :meth:`Shelve.sync` method.