blob: 67c0025fe9d944960c7a5c26009fd7702846f285 [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 ---
Georg Brandlac958ce2010-07-29 14:46:07 +00008:mod:`dbm.gnu` or :mod:`dbm.ndbm`. If none of these modules is installed, the
9slow-but-simple implementation in module :mod:`dbm.dumb` will be used. There
10is a `third party interface <http://www.jcea.es/programacion/pybsddb.htm>`_ to
Georg Brandlbb190152010-07-31 21:41:42 +000011the Oracle Berkeley 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
Georg Brandle8b0d612010-12-04 09:04:04 +000023 This function attempts to guess which of the several simple database modules
Georg Brandlac958ce2010-07-29 14:46:07 +000024 available --- :mod:`dbm.gnu`, :mod:`dbm.ndbm` or :mod:`dbm.dumb` --- should
25 be used to open a given file.
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000026
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
Georg Brandlc2a4f4f2009-04-10 09:03:43 +000033.. function:: open(filename, flag='r', mode=0o666)
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000034
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
Georg Brandl1a040582009-05-25 21:15:01 +000041 The optional *flag* argument can be:
42
43 +---------+-------------------------------------------+
44 | Value | Meaning |
45 +=========+===========================================+
46 | ``'r'`` | Open existing database for reading only |
47 | | (default) |
48 +---------+-------------------------------------------+
49 | ``'w'`` | Open existing database for reading and |
50 | | writing |
51 +---------+-------------------------------------------+
52 | ``'c'`` | Open database for reading and writing, |
53 | | creating it if it doesn't exist |
54 +---------+-------------------------------------------+
55 | ``'n'`` | Always create a new, empty database, open |
56 | | for reading and writing |
57 +---------+-------------------------------------------+
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000058
59 The optional *mode* argument is the Unix mode of the file, used only when the
60 database has to be created. It defaults to octal ``0o666`` (and will be
61 modified by the prevailing umask).
62
63
Georg Brandld9e833c2010-12-04 09:14:36 +000064The object returned by :func:`.open` supports the same basic functionality as
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000065dictionaries; keys and their corresponding values can be stored, retrieved, and
66deleted, and the :keyword:`in` operator and the :meth:`keys` method are
Georg Brandld9e833c2010-12-04 09:14:36 +000067available, as well as :meth:`get` and :meth:`setdefault`.
68
69.. versionchanged:: 3.2
70 :meth:`get` and :meth:`setdefault` are now available in all database modules.
71
72Key and values are always stored as bytes. This means that when
Brett Cannon7317c1e2008-11-25 19:19:17 +000073strings are used they are implicitly converted to the default encoding before
74being stored.
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000075
76The following example records some hostnames and a corresponding title, and
77then prints out the contents of the database::
78
79 import dbm
80
81 # Open database, creating it if necessary.
82 db = dbm.open('cache', 'c')
83
84 # Record some values
Brett Cannon7317c1e2008-11-25 19:19:17 +000085 db[b'hello'] = b'there'
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000086 db['www.python.org'] = 'Python Website'
87 db['www.cnn.com'] = 'Cable News Network'
88
Brett Cannon7317c1e2008-11-25 19:19:17 +000089 # Note that the keys are considered bytes now.
90 assert db[b'www.python.org'] == b'Python Website'
91 # Notice how the value is now in bytes.
92 assert db['www.cnn.com'] == b'Cable News Network'
93
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000094 # Loop through contents. Other dictionary methods
95 # such as .keys(), .values() also work.
96 for k, v in db.iteritems():
97 print(k, '\t', v)
98
99 # Storing a non-string key or value will raise an exception (most
100 # likely a TypeError).
101 db['www.yahoo.com'] = 4
102
103 # Close when done.
104 db.close()
105
106
107.. seealso::
108
109 Module :mod:`shelve`
110 Persistence module which stores non-string data.
111
112
113The individual submodules are described in the following sections.
114
115
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000116:mod:`dbm.gnu` --- GNU's reinterpretation of dbm
117------------------------------------------------
118
119.. module:: dbm.gnu
120 :platform: Unix
121 :synopsis: GNU's reinterpretation of dbm.
122
123
124This module is quite similar to the :mod:`dbm` module, but uses the GNU library
125``gdbm`` instead to provide some additional functionality. Please note that the
Brett Cannon7317c1e2008-11-25 19:19:17 +0000126file formats created by :mod:`dbm.gnu` and :mod:`dbm.ndbm` are incompatible.
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000127
128The :mod:`dbm.gnu` module provides an interface to the GNU DBM library.
Brett Cannon7317c1e2008-11-25 19:19:17 +0000129``dbm.gnu.gdbm`` objects behave like mappings (dictionaries), except that keys and
130values are always converted to bytes before storing. Printing a ``gdbm``
131object doesn't print the
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000132keys and values, and the :meth:`items` and :meth:`values` methods are not
133supported.
134
135.. exception:: error
136
Brett Cannon7317c1e2008-11-25 19:19:17 +0000137 Raised on :mod:`dbm.gnu`-specific errors, such as I/O errors. :exc:`KeyError` is
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000138 raised for general mapping errors like specifying an incorrect key.
139
140
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000141.. function:: open(filename[, flag[, mode]])
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000142
143 Open a ``gdbm`` database and return a :class:`gdbm` object. The *filename*
144 argument is the name of the database file.
145
146 The optional *flag* argument can be:
147
148 +---------+-------------------------------------------+
149 | Value | Meaning |
150 +=========+===========================================+
151 | ``'r'`` | Open existing database for reading only |
152 | | (default) |
153 +---------+-------------------------------------------+
154 | ``'w'`` | Open existing database for reading and |
155 | | writing |
156 +---------+-------------------------------------------+
157 | ``'c'`` | Open database for reading and writing, |
158 | | creating it if it doesn't exist |
159 +---------+-------------------------------------------+
160 | ``'n'`` | Always create a new, empty database, open |
161 | | for reading and writing |
162 +---------+-------------------------------------------+
163
164 The following additional characters may be appended to the flag to control
165 how the database is opened:
166
167 +---------+--------------------------------------------+
168 | Value | Meaning |
169 +=========+============================================+
170 | ``'f'`` | Open the database in fast mode. Writes |
171 | | to the database will not be synchronized. |
172 +---------+--------------------------------------------+
173 | ``'s'`` | Synchronized mode. This will cause changes |
174 | | to the database to be immediately written |
175 | | to the file. |
176 +---------+--------------------------------------------+
177 | ``'u'`` | Do not lock database. |
178 +---------+--------------------------------------------+
179
180 Not all flags are valid for all versions of ``gdbm``. The module constant
181 :const:`open_flags` is a string of supported flag characters. The exception
182 :exc:`error` is raised if an invalid flag is specified.
183
184 The optional *mode* argument is the Unix mode of the file, used only when the
Georg Brandlf4a41232008-05-26 17:55:52 +0000185 database has to be created. It defaults to octal ``0o666``.
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000186
187 In addition to the dictionary-like methods, ``gdbm`` objects have the
188 following methods:
189
190 .. method:: gdbm.firstkey()
191
192 It's possible to loop over every key in the database using this method and the
193 :meth:`nextkey` method. The traversal is ordered by ``gdbm``'s internal
194 hash values, and won't be sorted by the key values. This method returns
195 the starting key.
196
197 .. method:: gdbm.nextkey(key)
198
199 Returns the key that follows *key* in the traversal. The following code prints
200 every key in the database ``db``, without having to create a list in memory that
201 contains them all::
202
203 k = db.firstkey()
204 while k != None:
205 print(k)
206 k = db.nextkey(k)
207
208 .. method:: gdbm.reorganize()
209
210 If you have carried out a lot of deletions and would like to shrink the space
211 used by the ``gdbm`` file, this routine will reorganize the database. ``gdbm``
Brett Cannon7317c1e2008-11-25 19:19:17 +0000212 objects will not shorten the length of a database file except by using this
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000213 reorganization; otherwise, deleted file space will be kept and reused as new
214 (key, value) pairs are added.
215
216 .. method:: gdbm.sync()
217
218 When the database has been opened in fast mode, this method forces any
219 unwritten data to be written to the disk.
220
221
222:mod:`dbm.ndbm` --- Interface based on ndbm
223-------------------------------------------
224
225.. module:: dbm.ndbm
Georg Brandl116aa622007-08-15 14:28:22 +0000226 :platform: Unix
227 :synopsis: The standard "database" interface, based on ndbm.
228
229
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000230The :mod:`dbm.ndbm` module provides an interface to the Unix "(n)dbm" library.
231Dbm objects behave like mappings (dictionaries), except that keys and values are
Brett Cannon7317c1e2008-11-25 19:19:17 +0000232always stored as bytes. Printing a ``dbm`` object doesn't print the keys and
233values, and the :meth:`items` and :meth:`values` methods are not supported.
Georg Brandl116aa622007-08-15 14:28:22 +0000234
Georg Brandlac958ce2010-07-29 14:46:07 +0000235This module can be used with the "classic" ndbm interface or the GNU GDBM
236compatibility interface. On Unix, the :program:`configure` script will attempt
237to locate the appropriate header file to simplify building this module.
Georg Brandl116aa622007-08-15 14:28:22 +0000238
Georg Brandl116aa622007-08-15 14:28:22 +0000239.. exception:: error
240
Brett Cannon7317c1e2008-11-25 19:19:17 +0000241 Raised on :mod:`dbm.ndbm`-specific errors, such as I/O errors. :exc:`KeyError` is raised
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000242 for general mapping errors like specifying an incorrect key.
Georg Brandl116aa622007-08-15 14:28:22 +0000243
244
245.. data:: library
246
247 Name of the ``ndbm`` implementation library used.
248
249
250.. function:: open(filename[, flag[, mode]])
251
Brett Cannon7317c1e2008-11-25 19:19:17 +0000252 Open a dbm database and return a ``dbm`` object. The *filename* argument is the
Georg Brandlac958ce2010-07-29 14:46:07 +0000253 name of the database file (without the :file:`.dir` or :file:`.pag` extensions).
Georg Brandl116aa622007-08-15 14:28:22 +0000254
255 The optional *flag* argument must be one of these values:
256
257 +---------+-------------------------------------------+
258 | Value | Meaning |
259 +=========+===========================================+
260 | ``'r'`` | Open existing database for reading only |
261 | | (default) |
262 +---------+-------------------------------------------+
263 | ``'w'`` | Open existing database for reading and |
264 | | writing |
265 +---------+-------------------------------------------+
266 | ``'c'`` | Open database for reading and writing, |
267 | | creating it if it doesn't exist |
268 +---------+-------------------------------------------+
269 | ``'n'`` | Always create a new, empty database, open |
270 | | for reading and writing |
271 +---------+-------------------------------------------+
272
273 The optional *mode* argument is the Unix mode of the file, used only when the
Georg Brandlf4a41232008-05-26 17:55:52 +0000274 database has to be created. It defaults to octal ``0o666`` (and will be
Georg Brandl116aa622007-08-15 14:28:22 +0000275 modified by the prevailing umask).
276
277
Georg Brandl116aa622007-08-15 14:28:22 +0000278
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000279:mod:`dbm.dumb` --- Portable DBM implementation
280-----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000281
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000282.. module:: dbm.dumb
283 :synopsis: Portable implementation of the simple DBM interface.
Georg Brandl116aa622007-08-15 14:28:22 +0000284
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000285.. index:: single: databases
Georg Brandl116aa622007-08-15 14:28:22 +0000286
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000287.. note::
288
289 The :mod:`dbm.dumb` module is intended as a last resort fallback for the
Brett Cannon7317c1e2008-11-25 19:19:17 +0000290 :mod:`dbm` module when a more robust module is not available. The :mod:`dbm.dumb`
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000291 module is not written for speed and is not nearly as heavily used as the other
292 database modules.
293
294The :mod:`dbm.dumb` module provides a persistent dictionary-like interface which
Brett Cannon7317c1e2008-11-25 19:19:17 +0000295is written entirely in Python. Unlike other modules such as :mod:`dbm.gnu` no
Benjamin Peterson9a46cab2008-09-08 02:49:30 +0000296external library is required. As with other persistent mappings, the keys and
Brett Cannon7317c1e2008-11-25 19:19:17 +0000297values are always stored as bytes.
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000298
299The module defines the following:
300
301
302.. exception:: error
303
Brett Cannon7317c1e2008-11-25 19:19:17 +0000304 Raised on :mod:`dbm.dumb`-specific errors, such as I/O errors. :exc:`KeyError` is
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000305 raised for general mapping errors like specifying an incorrect key.
306
307
308.. function:: open(filename[, flag[, mode]])
309
Brett Cannon7317c1e2008-11-25 19:19:17 +0000310 Open a ``dumbdbm`` database and return a dumbdbm object. The *filename* argument is
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000311 the basename of the database file (without any specific extensions). When a
312 dumbdbm database is created, files with :file:`.dat` and :file:`.dir` extensions
313 are created.
314
315 The optional *flag* argument is currently ignored; the database is always opened
316 for update, and will be created if it does not exist.
317
318 The optional *mode* argument is the Unix mode of the file, used only when the
319 database has to be created. It defaults to octal ``0o666`` (and will be modified
320 by the prevailing umask).
321
322 In addition to the methods provided by the :class:`collections.MutableMapping` class,
323 :class:`dumbdbm` objects provide the following method:
324
325 .. method:: dumbdbm.sync()
326
327 Synchronize the on-disk directory and data files. This method is called
328 by the :meth:`Shelve.sync` method.