Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 1 | \section{Built-in module \sectcode{shelve}} |
| 2 | \stmodindex{shelve} |
| 3 | \stmodindex{pickle} |
| 4 | \bimodindex{dbm} |
| 5 | |
| 6 | A ``shelf'' is a persistent, dictionary-like object. The difference |
| 7 | with ``dbm'' databases is that the values (not the keys!) in a shelf |
| 8 | can be essentially arbitrary Python objects --- anything that the |
| 9 | \code{pickle} module can handle. This includes most class instances, |
| 10 | recursive data types, and objects containing lots of shared |
| 11 | sub-objects. The keys are ordinary strings. |
| 12 | |
| 13 | To summarize the interface (\code{key} is a string, \code{data} is an |
| 14 | arbitrary object): |
| 15 | |
| 16 | \begin{verbatim} |
| 17 | import shelve |
| 18 | |
| 19 | d = shelve.open(filename) # open, with (g)dbm filename -- no suffix |
| 20 | |
| 21 | d[key] = data # store data at key (overwrites old data if |
| 22 | # using an existing key) |
| 23 | data = d[key] # retrieve data at key (raise KeyError if no |
| 24 | # such key) |
| 25 | del d[key] # delete data stored at key (raises KeyError |
| 26 | # if no such key) |
| 27 | flag = d.has_key(key) # true if the key exists |
| 28 | list = d.keys() # a list of all existing keys (slow!) |
| 29 | |
| 30 | d.close() # close it |
| 31 | \end{verbatim} |
| 32 | |
Guido van Rossum | 5680b95 | 1995-02-16 16:29:01 +0000 | [diff] [blame] | 33 | Restrictions: |
| 34 | |
| 35 | \begin{itemize} |
| 36 | |
| 37 | \item |
| 38 | The choice of which database package will be used (e.g. dbm or gdbm) |
| 39 | depends on which interface is available. Therefore it isn't safe to |
| 40 | open the database directly using dbm. The database is also |
| 41 | (unfortunately) subject to the limitations of dbm, if it is used --- |
| 42 | this means that (the pickled representation of) the objects stored in |
| 43 | the database should be fairly small, and in rare cases key collisions |
| 44 | may cause the database to refuse updates. |
| 45 | |
| 46 | \item |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 47 | Dependent on the implementation, closing a persistent dictionary may |
| 48 | or may not be necessary to flush changes to disk. |
| 49 | |
Guido van Rossum | 5680b95 | 1995-02-16 16:29:01 +0000 | [diff] [blame] | 50 | \item |
| 51 | The \code{shelve} module does not support {\em concurrent} access to |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 52 | shelved objects. Two programs should not try to simultaneously access |
| 53 | the same shelf. |
Guido van Rossum | 5680b95 | 1995-02-16 16:29:01 +0000 | [diff] [blame] | 54 | |
| 55 | \end{itemize} |