Debian Codegraph @

Doc/library/dbm.rst

raw
1 :mod:`!dbm` --- Interfaces to Unix "databases"
2 ==============================================
3
4 .. module:: dbm
5 :synopsis: Interfaces to various Unix "database" formats.
6
7 **Source code:** :source:`Lib/dbm/__init__.py`
8
9 --------------
10
11 :mod:`dbm` is a generic interface to variants of the DBM database:
12
13 * :mod:`dbm.sqlite3`
14 * :mod:`dbm.gnu`
15 * :mod:`dbm.ndbm`
16
17 If none of these modules are installed, the
18 slow-but-simple implementation in module :mod:`dbm.dumb` will be used. There
19 is a `third party interface <https://www.jcea.es/programacion/pybsddb.htm>`_ to
20 the Oracle Berkeley DB.
21
22 .. exception:: error
23
24 A tuple containing the exceptions that can be raised by each of the supported
25 modules, with a unique exception also named :exc:`dbm.error` as the first
26 item --- the latter is used when :exc:`dbm.error` is raised.
27
28
29 .. function:: whichdb(filename)
30
31 This function attempts to guess which of the several simple database modules
32 available --- :mod:`dbm.sqlite3`, :mod:`dbm.gnu`, :mod:`dbm.ndbm`,
33 or :mod:`dbm.dumb` --- should be used to open a given file.
34
35 Return one of the following values:
36
37 * ``None`` if the file can't be opened because it's unreadable or doesn't exist
38 * the empty string (``''``) if the file's format can't be guessed
39 * a string containing the required module name, such as ``'dbm.ndbm'`` or ``'dbm.gnu'``
40
41 .. versionchanged:: 3.11
42 *filename* accepts a :term:`path-like object`.
43
44 .. Substitutions for the open() flag param docs;
45 all submodules use the same text.
46
47 .. |flag_r| replace::
48 Open existing database for reading only.
49
50 .. |flag_w| replace::
51 Open existing database for reading and writing.
52
53 .. |flag_c| replace::
54 Open database for reading and writing, creating it if it doesn't exist.
55
56 .. |flag_n| replace::
57 Always create a new, empty database, open for reading and writing.
58
59 .. |mode_param_doc| replace::
60 The Unix file access mode of the file (default: octal ``0o666``),
61 used only when the database has to be created.
62
63 .. function:: open(file, flag='r', mode=0o666)
64
65 Open a database and return the corresponding database object.
66
67 :param file:
68 The database file to open.
69
70 If the database file already exists, the :func:`whichdb` function is used to
71 determine its type and the appropriate module is used; if it does not exist,
72 the first submodule listed above that can be imported is used.
73 :type file: :term:`path-like object`
74
75 :param str flag:
76 * ``'r'`` (default): |flag_r|
77 * ``'w'``: |flag_w|
78 * ``'c'``: |flag_c|
79 * ``'n'``: |flag_n|
80
81 :param int mode:
82 |mode_param_doc|
83
84 .. versionchanged:: 3.11
85 *file* accepts a :term:`path-like object`.
86
87 The object returned by :func:`~dbm.open` supports the basic
88 functionality of mutable :term:`mappings <mapping>`;
89 keys and their corresponding values can be stored, retrieved, and
90 deleted, and iteration, the :keyword:`in` operator and methods :meth:`!keys`,
91 :meth:`!get`, :meth:`!setdefault` and :meth:`!clear` are available.
92 The :meth:`!keys` method returns a list instead of a view object.
93 The :meth:`!setdefault` method requires two arguments.
94
95 Key and values are always stored as :class:`bytes`. This means that when
96 strings are used they are implicitly converted to the default encoding before
97 being stored.
98
99 These objects also support being used in a :keyword:`with` statement, which
100 will automatically close them when done.
101
102 .. versionchanged:: 3.2
103 :meth:`!get` and :meth:`!setdefault` methods are now available for all
104 :mod:`dbm` backends.
105
106 .. versionchanged:: 3.4
107 Added native support for the context management protocol to the objects
108 returned by :func:`~dbm.open`.
109
110 .. versionchanged:: 3.8
111 Deleting a key from a read-only database raises a database module specific exception
112 instead of :exc:`KeyError`.
113
114 .. versionchanged:: 3.13
115 :meth:`!clear` methods are now available for all :mod:`dbm` backends.
116
117
118 The following example records some hostnames and a corresponding title, and
119 then prints out the contents of the database::
120
121 import dbm
122
123 # Open database, creating it if necessary.
124 with dbm.open('cache', 'c') as db:
125
126 # Record some values
127 db[b'hello'] = b'there'
128 db['www.python.org'] = 'Python Website'
129 db['www.cnn.com'] = 'Cable News Network'
130
131 # Note that the keys are considered bytes now.
132 assert db[b'www.python.org'] == b'Python Website'
133 # Notice how the value is now in bytes.
134 assert db['www.cnn.com'] == b'Cable News Network'
135
136 # Often-used methods of the dict interface work too.
137 print(db.get('python.org', b'not present'))
138
139 # Storing a non-string key or value will raise an exception (most
140 # likely a TypeError).
141 db['www.yahoo.com'] = 4
142
143 # db is automatically closed when leaving the with statement.
144
145
146 .. seealso::
147
148 Module :mod:`shelve`
149 Persistence module which stores non-string data.
150
151
152 The individual submodules are described in the following sections.
153
154 :mod:`dbm.sqlite3` --- SQLite backend for dbm
155 ---------------------------------------------
156
157 .. module:: dbm.sqlite3
158 :platform: All
159 :synopsis: SQLite backend for dbm
160
161 .. versionadded:: 3.13
162
163 **Source code:** :source:`Lib/dbm/sqlite3.py`
164
165 --------------
166
167 This module uses the standard library :mod:`sqlite3` module to provide an
168 SQLite backend for the :mod:`dbm` module.
169 The files created by :mod:`dbm.sqlite3` can thus be opened by :mod:`sqlite3`,
170 or any other SQLite browser, including the SQLite CLI.
171
172 .. include:: ../includes/wasm-notavail.rst
173
174 .. function:: open(filename, /, flag="r", mode=0o666)
175
176 Open an SQLite database.
177
178 :param filename:
179 The path to the database to be opened.
180 :type filename: :term:`path-like object`
181
182 :param str flag:
183
184 * ``'r'`` (default): |flag_r|
185 * ``'w'``: |flag_w|
186 * ``'c'``: |flag_c|
187 * ``'n'``: |flag_n|
188
189 :param mode:
190 The Unix file access mode of the file (default: octal ``0o666``),
191 used only when the database has to be created.
192
193 The returned database object behaves similar to a mutable :term:`mapping`,
194 but the :meth:`!keys` method returns a list, and
195 the :meth:`!setdefault` method requires two arguments.
196 It also supports a "closing" context manager via the :keyword:`with` keyword.
197
198 The following method is also provided:
199
200 .. method:: sqlite3.close()
201
202 Close the SQLite database.
203
204
205 :mod:`dbm.gnu` --- GNU database manager
206 ---------------------------------------
207
208 .. module:: dbm.gnu
209 :platform: Unix
210 :synopsis: GNU database manager
211
212 **Source code:** :source:`Lib/dbm/gnu.py`
213
214 --------------
215
216 The :mod:`dbm.gnu` module provides an interface to the :abbr:`GDBM (GNU dbm)`
217 library, similar to the :mod:`dbm.ndbm` module, but with additional
218 functionality like crash tolerance.
219
220 .. note::
221
222 The file formats created by :mod:`dbm.gnu` and :mod:`dbm.ndbm` are incompatible
223 and can not be used interchangeably.
224
225 .. include:: ../includes/wasm-mobile-notavail.rst
226
227 .. exception:: error
228
229 Raised on :mod:`dbm.gnu`-specific errors, such as I/O errors. :exc:`KeyError` is
230 raised for general mapping errors like specifying an incorrect key.
231
232
233 .. data:: open_flags
234
235 A string of characters the *flag* parameter of :meth:`~dbm.gnu.open` supports.
236
237
238 .. function:: open(filename, flag="r", mode=0o666, /)
239
240 Open a GDBM database and return a :class:`!gdbm` object.
241
242 :param filename:
243 The database file to open.
244 :type filename: :term:`path-like object`
245
246 :param str flag:
247 * ``'r'`` (default): |flag_r|
248 * ``'w'``: |flag_w|
249 * ``'c'``: |flag_c|
250 * ``'n'``: |flag_n|
251
252 The following additional characters may be appended
253 to control how the database is opened:
254
255 * ``'f'``: Open the database in fast mode.
256 Writes to the database will not be synchronized.
257 * ``'s'``: Synchronized mode.
258 Changes to the database will be written immediately to the file.
259 * ``'u'``: Do not lock database.
260
261 Not all flags are valid for all versions of GDBM.
262 See the :data:`open_flags` member for a list of supported flag characters.
263
264 :param int mode:
265 |mode_param_doc|
266
267 :raises error:
268 If an invalid *flag* argument is passed.
269
270 .. versionchanged:: 3.11
271 *filename* accepts a :term:`path-like object`.
272
273 :class:`!gdbm` objects behave similar to mutable :term:`mappings <mapping>`,
274 but methods :meth:`!items`, :meth:`!values`, :meth:`!pop`, :meth:`!popitem`,
275 and :meth:`!update` are not supported,
276 the :meth:`!keys` method returns a list, and
277 the :meth:`!setdefault` method requires two arguments.
278 It also supports a "closing" context manager via the :keyword:`with` keyword.
279
280 .. versionchanged:: 3.2
281 Added the :meth:`!get` and :meth:`!setdefault` methods.
282
283 .. versionchanged:: 3.13
284 Added the :meth:`!clear` method.
285
286 The following methods are also provided:
287
288 .. method:: gdbm.close()
289
290 Close the GDBM database.
291
292 .. method:: gdbm.firstkey()
293
294 It's possible to loop over every key in the database using this method and the
295 :meth:`nextkey` method. The traversal is ordered by GDBM's internal
296 hash values, and won't be sorted by the key values. This method returns
297 the starting key.
298
299 .. method:: gdbm.nextkey(key)
300
301 Returns the key that follows *key* in the traversal. The following code prints
302 every key in the database ``db``, without having to create a list in memory that
303 contains them all::
304
305 k = db.firstkey()
306 while k is not None:
307 print(k)
308 k = db.nextkey(k)
309
310 .. method:: gdbm.reorganize()
311
312 If you have carried out a lot of deletions and would like to shrink the space
313 used by the GDBM file, this routine will reorganize the database. :class:`!gdbm`
314 objects will not shorten the length of a database file except by using this
315 reorganization; otherwise, deleted file space will be kept and reused as new
316 (key, value) pairs are added.
317
318 .. method:: gdbm.sync()
319
320 When the database has been opened in fast mode, this method forces any
321 unwritten data to be written to the disk.
322
323
324 :mod:`dbm.ndbm` --- New Database Manager
325 ----------------------------------------
326
327 .. module:: dbm.ndbm
328 :platform: Unix
329 :synopsis: The New Database Manager
330
331 **Source code:** :source:`Lib/dbm/ndbm.py`
332
333 --------------
334
335 The :mod:`dbm.ndbm` module provides an interface to the
336 :abbr:`NDBM (New Database Manager)` library.
337 This module can be used with the "classic" NDBM interface or the
338 :abbr:`GDBM (GNU dbm)` compatibility interface.
339
340 .. note::
341
342 The file formats created by :mod:`dbm.gnu` and :mod:`dbm.ndbm` are incompatible
343 and can not be used interchangeably.
344
345 .. warning::
346
347 The NDBM library shipped as part of macOS has an undocumented limitation on the
348 size of values, which can result in corrupted database files
349 when storing values larger than this limit. Reading such corrupted files can
350 result in a hard crash (segmentation fault).
351
352 .. include:: ../includes/wasm-mobile-notavail.rst
353
354 .. exception:: error
355
356 Raised on :mod:`dbm.ndbm`-specific errors, such as I/O errors. :exc:`KeyError` is raised
357 for general mapping errors like specifying an incorrect key.
358
359
360 .. data:: library
361
362 Name of the NDBM implementation library used.
363
364
365 .. function:: open(filename, flag="r", mode=0o666, /)
366
367 Open an NDBM database and return an :class:`!ndbm` object.
368
369 :param filename:
370 The basename of the database file
371 (without the :file:`.dir` or :file:`.pag` extensions).
372 :type filename: :term:`path-like object`
373
374 :param str flag:
375 * ``'r'`` (default): |flag_r|
376 * ``'w'``: |flag_w|
377 * ``'c'``: |flag_c|
378 * ``'n'``: |flag_n|
379
380 :param int mode:
381 |mode_param_doc|
382
383 .. versionchanged:: 3.11
384 Accepts :term:`path-like object` for filename.
385
386 :class:`!ndbm` objects behave similar to mutable :term:`mappings <mapping>`,
387 but methods :meth:`!items`, :meth:`!values`, :meth:`!pop`, :meth:`!popitem`,
388 and :meth:`!update` are not supported,
389 the :meth:`!keys` method returns a list, and
390 the :meth:`!setdefault` method requires two arguments.
391 It also supports a "closing" context manager via the :keyword:`with` keyword.
392
393 .. versionchanged:: 3.2
394 Added the :meth:`!get` and :meth:`!setdefault` methods.
395
396 .. versionchanged:: 3.13
397 Added the :meth:`!clear` method.
398
399 The following method is also provided:
400
401 .. method:: ndbm.close()
402
403 Close the NDBM database.
404
405
406 :mod:`dbm.dumb` --- Portable DBM implementation
407 -----------------------------------------------
408
409 .. module:: dbm.dumb
410 :synopsis: Portable implementation of the simple DBM interface.
411
412 **Source code:** :source:`Lib/dbm/dumb.py`
413
414 .. index:: single: databases
415
416 .. note::
417
418 The :mod:`dbm.dumb` module is intended as a last resort fallback for the
419 :mod:`dbm` module when a more robust module is not available. The :mod:`dbm.dumb`
420 module is not written for speed and is not nearly as heavily used as the other
421 database modules.
422
423 --------------
424
425 The :mod:`dbm.dumb` module provides a persistent :class:`dict`-like
426 interface which is written entirely in Python.
427 Unlike other :mod:`dbm` backends, such as :mod:`dbm.gnu`, no
428 external library is required.
429
430 The :mod:`!dbm.dumb` module defines the following:
431
432 .. exception:: error
433
434 Raised on :mod:`dbm.dumb`-specific errors, such as I/O errors. :exc:`KeyError` is
435 raised for general mapping errors like specifying an incorrect key.
436
437
438 .. function:: open(filename, flag="c", mode=0o666)
439
440 Open a :mod:`!dbm.dumb` database.
441
442 :param filename:
443 The basename of the database file (without extensions).
444 A new database creates the following files:
445
446 - :file:`{filename}.dat`
447 - :file:`{filename}.dir`
448 :type database: :term:`path-like object`
449
450 :param str flag:
451 * ``'r'``: |flag_r|
452 * ``'w'``: |flag_w|
453 * ``'c'`` (default): |flag_c|
454 * ``'n'``: |flag_n|
455
456 :param int mode:
457 |mode_param_doc|
458
459 .. warning::
460 It is possible to crash the Python interpreter when loading a database
461 with a sufficiently large/complex entry due to stack depth limitations in
462 Python's AST compiler.
463
464 .. versionchanged:: 3.5
465 :func:`~dbm.dumb.open` always creates a new database when *flag* is ``'n'``.
466
467 .. versionchanged:: 3.8
468 A database opened read-only if *flag* is ``'r'``.
469 A database is not created if it does not exist if *flag* is ``'r'`` or ``'w'``.
470
471 .. versionchanged:: 3.11
472 *filename* accepts a :term:`path-like object`.
473
474 The returned database object behaves similar to a mutable :term:`mapping`,
475 but the :meth:`!keys` and :meth:`!items` methods return lists, and
476 the :meth:`!setdefault` method requires two arguments.
477 It also supports a "closing" context manager via the :keyword:`with` keyword.
478
479 The following methods are also provided:
480
481 .. method:: dumbdbm.close()
482
483 Close the database.
484
485 .. method:: dumbdbm.sync()
486
487 Synchronize the on-disk directory and data files. This method is called
488 by the :meth:`shelve.Shelf.sync` method.