blob: 57ae547b833cc0eb2a76cdfc4ed3d1f5d5b24794 [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
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04007**Source code:** :source:`Lib/dbm/__init__.py`
8
9--------------
10
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000011:mod:`dbm` is a generic interface to variants of the DBM database ---
Georg Brandlac958ce2010-07-29 14:46:07 +000012:mod:`dbm.gnu` or :mod:`dbm.ndbm`. If none of these modules is installed, the
13slow-but-simple implementation in module :mod:`dbm.dumb` will be used. There
Georg Brandl5d941342016-02-26 19:37:12 +010014is a `third party interface <https://www.jcea.es/programacion/pybsddb.htm>`_ to
Georg Brandlbb190152010-07-31 21:41:42 +000015the Oracle Berkeley DB.
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000016
17
18.. exception:: error
19
20 A tuple containing the exceptions that can be raised by each of the supported
21 modules, with a unique exception also named :exc:`dbm.error` as the first
22 item --- the latter is used when :exc:`dbm.error` is raised.
23
24
25.. function:: whichdb(filename)
26
Georg Brandle8b0d612010-12-04 09:04:04 +000027 This function attempts to guess which of the several simple database modules
Georg Brandlac958ce2010-07-29 14:46:07 +000028 available --- :mod:`dbm.gnu`, :mod:`dbm.ndbm` or :mod:`dbm.dumb` --- should
29 be used to open a given file.
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000030
31 Returns one of the following values: ``None`` if the file can't be opened
32 because it's unreadable or doesn't exist; the empty string (``''``) if the
33 file's format can't be guessed; or a string containing the required module
34 name, such as ``'dbm.ndbm'`` or ``'dbm.gnu'``.
35
36
Éric Araujo5c1a0c92011-04-20 19:11:12 +020037.. function:: open(file, flag='r', mode=0o666)
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000038
Éric Araujo5c1a0c92011-04-20 19:11:12 +020039 Open the database file *file* and return a corresponding object.
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000040
41 If the database file already exists, the :func:`whichdb` function is used to
42 determine its type and the appropriate module is used; if it does not exist,
43 the first module listed above that can be imported is used.
44
Georg Brandl1a040582009-05-25 21:15:01 +000045 The optional *flag* argument can be:
46
47 +---------+-------------------------------------------+
48 | Value | Meaning |
49 +=========+===========================================+
50 | ``'r'`` | Open existing database for reading only |
51 | | (default) |
52 +---------+-------------------------------------------+
53 | ``'w'`` | Open existing database for reading and |
54 | | writing |
55 +---------+-------------------------------------------+
56 | ``'c'`` | Open database for reading and writing, |
57 | | creating it if it doesn't exist |
58 +---------+-------------------------------------------+
59 | ``'n'`` | Always create a new, empty database, open |
60 | | for reading and writing |
61 +---------+-------------------------------------------+
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000062
63 The optional *mode* argument is the Unix mode of the file, used only when the
64 database has to be created. It defaults to octal ``0o666`` (and will be
65 modified by the prevailing umask).
66
67
Georg Brandld9e833c2010-12-04 09:14:36 +000068The object returned by :func:`.open` supports the same basic functionality as
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000069dictionaries; keys and their corresponding values can be stored, retrieved, and
70deleted, and the :keyword:`in` operator and the :meth:`keys` method are
Georg Brandld9e833c2010-12-04 09:14:36 +000071available, as well as :meth:`get` and :meth:`setdefault`.
72
73.. versionchanged:: 3.2
74 :meth:`get` and :meth:`setdefault` are now available in all database modules.
75
Xiang Zhang4fb0b8b2018-12-12 20:46:55 +080076.. versionchanged:: 3.8
77 Deleting a key from a read-only database raises database module specific error
78 instead of :exc:`KeyError`.
79
Georg Brandld9e833c2010-12-04 09:14:36 +000080Key and values are always stored as bytes. This means that when
Brett Cannon7317c1e2008-11-25 19:19:17 +000081strings are used they are implicitly converted to the default encoding before
82being stored.
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000083
Nick Coghlanc610aba2013-11-17 15:59:51 +100084These objects also support being used in a :keyword:`with` statement, which
85will automatically close them when done.
86
87.. versionchanged:: 3.4
88 Added native support for the context management protocol to the objects
89 returned by :func:`.open`.
90
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000091The following example records some hostnames and a corresponding title, and
92then prints out the contents of the database::
93
94 import dbm
95
96 # Open database, creating it if necessary.
Nick Coghlanc610aba2013-11-17 15:59:51 +100097 with dbm.open('cache', 'c') as db:
Georg Brandl0a7ac7d2008-05-26 10:29:35 +000098
Nick Coghlanc610aba2013-11-17 15:59:51 +100099 # Record some values
100 db[b'hello'] = b'there'
101 db['www.python.org'] = 'Python Website'
102 db['www.cnn.com'] = 'Cable News Network'
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000103
Nick Coghlanc610aba2013-11-17 15:59:51 +1000104 # Note that the keys are considered bytes now.
105 assert db[b'www.python.org'] == b'Python Website'
106 # Notice how the value is now in bytes.
107 assert db['www.cnn.com'] == b'Cable News Network'
Brett Cannon7317c1e2008-11-25 19:19:17 +0000108
Nick Coghlanc610aba2013-11-17 15:59:51 +1000109 # Often-used methods of the dict interface work too.
110 print(db.get('python.org', b'not present'))
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000111
Nick Coghlanc610aba2013-11-17 15:59:51 +1000112 # Storing a non-string key or value will raise an exception (most
113 # likely a TypeError).
114 db['www.yahoo.com'] = 4
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000115
Nick Coghlanc610aba2013-11-17 15:59:51 +1000116 # db is automatically closed when leaving the with statement.
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000117
118
119.. seealso::
120
121 Module :mod:`shelve`
122 Persistence module which stores non-string data.
123
124
125The individual submodules are described in the following sections.
126
127
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000128:mod:`dbm.gnu` --- GNU's reinterpretation of dbm
129------------------------------------------------
130
131.. module:: dbm.gnu
132 :platform: Unix
133 :synopsis: GNU's reinterpretation of dbm.
134
Terry Jan Reedydcb6c882016-06-22 22:46:34 -0400135**Source code:** :source:`Lib/dbm/gnu.py`
136
137--------------
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000138
139This module is quite similar to the :mod:`dbm` module, but uses the GNU library
140``gdbm`` instead to provide some additional functionality. Please note that the
Brett Cannon7317c1e2008-11-25 19:19:17 +0000141file formats created by :mod:`dbm.gnu` and :mod:`dbm.ndbm` are incompatible.
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000142
143The :mod:`dbm.gnu` module provides an interface to the GNU DBM library.
Brett Cannon7317c1e2008-11-25 19:19:17 +0000144``dbm.gnu.gdbm`` objects behave like mappings (dictionaries), except that keys and
145values are always converted to bytes before storing. Printing a ``gdbm``
146object doesn't print the
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000147keys and values, and the :meth:`items` and :meth:`values` methods are not
148supported.
149
150.. exception:: error
151
Brett Cannon7317c1e2008-11-25 19:19:17 +0000152 Raised on :mod:`dbm.gnu`-specific errors, such as I/O errors. :exc:`KeyError` is
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000153 raised for general mapping errors like specifying an incorrect key.
154
155
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000156.. function:: open(filename[, flag[, mode]])
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000157
158 Open a ``gdbm`` database and return a :class:`gdbm` object. The *filename*
159 argument is the name of the database file.
160
161 The optional *flag* argument can be:
162
163 +---------+-------------------------------------------+
164 | Value | Meaning |
165 +=========+===========================================+
166 | ``'r'`` | Open existing database for reading only |
167 | | (default) |
168 +---------+-------------------------------------------+
169 | ``'w'`` | Open existing database for reading and |
170 | | writing |
171 +---------+-------------------------------------------+
172 | ``'c'`` | Open database for reading and writing, |
173 | | creating it if it doesn't exist |
174 +---------+-------------------------------------------+
175 | ``'n'`` | Always create a new, empty database, open |
176 | | for reading and writing |
177 +---------+-------------------------------------------+
178
179 The following additional characters may be appended to the flag to control
180 how the database is opened:
181
182 +---------+--------------------------------------------+
183 | Value | Meaning |
184 +=========+============================================+
185 | ``'f'`` | Open the database in fast mode. Writes |
186 | | to the database will not be synchronized. |
187 +---------+--------------------------------------------+
188 | ``'s'`` | Synchronized mode. This will cause changes |
189 | | to the database to be immediately written |
190 | | to the file. |
191 +---------+--------------------------------------------+
192 | ``'u'`` | Do not lock database. |
193 +---------+--------------------------------------------+
194
195 Not all flags are valid for all versions of ``gdbm``. The module constant
196 :const:`open_flags` is a string of supported flag characters. The exception
197 :exc:`error` is raised if an invalid flag is specified.
198
199 The optional *mode* argument is the Unix mode of the file, used only when the
Georg Brandlf4a41232008-05-26 17:55:52 +0000200 database has to be created. It defaults to octal ``0o666``.
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000201
202 In addition to the dictionary-like methods, ``gdbm`` objects have the
203 following methods:
204
205 .. method:: gdbm.firstkey()
206
207 It's possible to loop over every key in the database using this method and the
208 :meth:`nextkey` method. The traversal is ordered by ``gdbm``'s internal
209 hash values, and won't be sorted by the key values. This method returns
210 the starting key.
211
212 .. method:: gdbm.nextkey(key)
213
214 Returns the key that follows *key* in the traversal. The following code prints
215 every key in the database ``db``, without having to create a list in memory that
216 contains them all::
217
218 k = db.firstkey()
219 while k != None:
220 print(k)
221 k = db.nextkey(k)
222
223 .. method:: gdbm.reorganize()
224
225 If you have carried out a lot of deletions and would like to shrink the space
226 used by the ``gdbm`` file, this routine will reorganize the database. ``gdbm``
Brett Cannon7317c1e2008-11-25 19:19:17 +0000227 objects will not shorten the length of a database file except by using this
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000228 reorganization; otherwise, deleted file space will be kept and reused as new
229 (key, value) pairs are added.
230
231 .. method:: gdbm.sync()
232
233 When the database has been opened in fast mode, this method forces any
234 unwritten data to be written to the disk.
235
Jesus Ceaac4b7f72014-06-25 13:05:31 +0200236 .. method:: gdbm.close()
237
238 Close the ``gdbm`` database.
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000239
240:mod:`dbm.ndbm` --- Interface based on ndbm
241-------------------------------------------
242
243.. module:: dbm.ndbm
Georg Brandl116aa622007-08-15 14:28:22 +0000244 :platform: Unix
245 :synopsis: The standard "database" interface, based on ndbm.
246
Terry Jan Reedydcb6c882016-06-22 22:46:34 -0400247**Source code:** :source:`Lib/dbm/ndbm.py`
248
249--------------
Georg Brandl116aa622007-08-15 14:28:22 +0000250
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000251The :mod:`dbm.ndbm` module provides an interface to the Unix "(n)dbm" library.
252Dbm objects behave like mappings (dictionaries), except that keys and values are
Brett Cannon7317c1e2008-11-25 19:19:17 +0000253always stored as bytes. Printing a ``dbm`` object doesn't print the keys and
254values, and the :meth:`items` and :meth:`values` methods are not supported.
Georg Brandl116aa622007-08-15 14:28:22 +0000255
Georg Brandlac958ce2010-07-29 14:46:07 +0000256This module can be used with the "classic" ndbm interface or the GNU GDBM
257compatibility interface. On Unix, the :program:`configure` script will attempt
258to locate the appropriate header file to simplify building this module.
Georg Brandl116aa622007-08-15 14:28:22 +0000259
Georg Brandl116aa622007-08-15 14:28:22 +0000260.. exception:: error
261
Brett Cannon7317c1e2008-11-25 19:19:17 +0000262 Raised on :mod:`dbm.ndbm`-specific errors, such as I/O errors. :exc:`KeyError` is raised
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000263 for general mapping errors like specifying an incorrect key.
Georg Brandl116aa622007-08-15 14:28:22 +0000264
265
266.. data:: library
267
268 Name of the ``ndbm`` implementation library used.
269
270
271.. function:: open(filename[, flag[, mode]])
272
Jesus Ceaac4b7f72014-06-25 13:05:31 +0200273 Open a dbm database and return a ``ndbm`` object. The *filename* argument is the
Georg Brandlac958ce2010-07-29 14:46:07 +0000274 name of the database file (without the :file:`.dir` or :file:`.pag` extensions).
Georg Brandl116aa622007-08-15 14:28:22 +0000275
276 The optional *flag* argument must be one of these values:
277
278 +---------+-------------------------------------------+
279 | Value | Meaning |
280 +=========+===========================================+
281 | ``'r'`` | Open existing database for reading only |
282 | | (default) |
283 +---------+-------------------------------------------+
284 | ``'w'`` | Open existing database for reading and |
285 | | writing |
286 +---------+-------------------------------------------+
287 | ``'c'`` | Open database for reading and writing, |
288 | | creating it if it doesn't exist |
289 +---------+-------------------------------------------+
290 | ``'n'`` | Always create a new, empty database, open |
291 | | for reading and writing |
292 +---------+-------------------------------------------+
293
294 The optional *mode* argument is the Unix mode of the file, used only when the
Georg Brandlf4a41232008-05-26 17:55:52 +0000295 database has to be created. It defaults to octal ``0o666`` (and will be
Georg Brandl116aa622007-08-15 14:28:22 +0000296 modified by the prevailing umask).
297
Jesus Ceaac4b7f72014-06-25 13:05:31 +0200298 In addition to the dictionary-like methods, ``ndbm`` objects
299 provide the following method:
300
301 .. method:: ndbm.close()
302
303 Close the ``ndbm`` database.
Georg Brandl116aa622007-08-15 14:28:22 +0000304
Georg Brandl116aa622007-08-15 14:28:22 +0000305
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000306:mod:`dbm.dumb` --- Portable DBM implementation
307-----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000308
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000309.. module:: dbm.dumb
310 :synopsis: Portable implementation of the simple DBM interface.
Georg Brandl116aa622007-08-15 14:28:22 +0000311
Terry Jan Reedydcb6c882016-06-22 22:46:34 -0400312**Source code:** :source:`Lib/dbm/dumb.py`
313
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000314.. index:: single: databases
Georg Brandl116aa622007-08-15 14:28:22 +0000315
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000316.. note::
317
318 The :mod:`dbm.dumb` module is intended as a last resort fallback for the
Brett Cannon7317c1e2008-11-25 19:19:17 +0000319 :mod:`dbm` module when a more robust module is not available. The :mod:`dbm.dumb`
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000320 module is not written for speed and is not nearly as heavily used as the other
321 database modules.
322
Terry Jan Reedydcb6c882016-06-22 22:46:34 -0400323--------------
324
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000325The :mod:`dbm.dumb` module provides a persistent dictionary-like interface which
Brett Cannon7317c1e2008-11-25 19:19:17 +0000326is written entirely in Python. Unlike other modules such as :mod:`dbm.gnu` no
Benjamin Peterson9a46cab2008-09-08 02:49:30 +0000327external library is required. As with other persistent mappings, the keys and
Brett Cannon7317c1e2008-11-25 19:19:17 +0000328values are always stored as bytes.
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000329
330The module defines the following:
331
332
333.. exception:: error
334
Brett Cannon7317c1e2008-11-25 19:19:17 +0000335 Raised on :mod:`dbm.dumb`-specific errors, such as I/O errors. :exc:`KeyError` is
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000336 raised for general mapping errors like specifying an incorrect key.
337
338
339.. function:: open(filename[, flag[, mode]])
340
Brett Cannon7317c1e2008-11-25 19:19:17 +0000341 Open a ``dumbdbm`` database and return a dumbdbm object. The *filename* argument is
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000342 the basename of the database file (without any specific extensions). When a
343 dumbdbm database is created, files with :file:`.dat` and :file:`.dir` extensions
344 are created.
345
Serhiy Storchaka6c85efa52018-02-05 22:47:31 +0200346 The optional *flag* argument can be:
347
348 +---------+-------------------------------------------+
349 | Value | Meaning |
350 +=========+===========================================+
351 | ``'r'`` | Open existing database for reading only |
352 | | (default) |
353 +---------+-------------------------------------------+
354 | ``'w'`` | Open existing database for reading and |
355 | | writing |
356 +---------+-------------------------------------------+
357 | ``'c'`` | Open database for reading and writing, |
358 | | creating it if it doesn't exist |
359 +---------+-------------------------------------------+
360 | ``'n'`` | Always create a new, empty database, open |
361 | | for reading and writing |
362 +---------+-------------------------------------------+
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000363
364 The optional *mode* argument is the Unix mode of the file, used only when the
365 database has to be created. It defaults to octal ``0o666`` (and will be modified
366 by the prevailing umask).
367
Brett Cannon10485eb2018-03-09 15:58:40 -0800368 .. warning::
369 It is possible to crash the Python interpreter when loading a database
370 with a sufficiently large/complex entry due to stack depth limitations in
371 Python's AST compiler.
372
Serhiy Storchakab398d332014-06-10 21:16:00 +0300373 .. versionchanged:: 3.5
374 :func:`.open` always creates a new database when the flag has the value
375 ``'n'``.
376
Serhiy Storchaka6c85efa52018-02-05 22:47:31 +0200377 .. versionchanged:: 3.8
378 A database opened with flags ``'r'`` is now read-only. Opening with
379 flags ``'r'`` and ``'w'`` no longer creates a database if it does not
380 exist.
Serhiy Storchaka0122ae92016-07-06 12:21:58 +0300381
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300382 In addition to the methods provided by the
383 :class:`collections.abc.MutableMapping` class, :class:`dumbdbm` objects
Jesus Ceaac4b7f72014-06-25 13:05:31 +0200384 provide the following methods:
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000385
386 .. method:: dumbdbm.sync()
387
388 Synchronize the on-disk directory and data files. This method is called
389 by the :meth:`Shelve.sync` method.
Jesus Ceaac4b7f72014-06-25 13:05:31 +0200390
391 .. method:: dumbdbm.close()
392
393 Close the ``dumbdbm`` database.
394