blob: 05b3a93d3e3c743f17838feb3ae337ea8e81cc79 [file] [log] [blame]
Guido van Rossum470be141995-03-17 16:07:09 +00001\section{Standard Module \sectcode{shelve}}
Guido van Rossume47da0a1997-07-17 16:34:52 +00002\label{module-shelve}
Guido van Rossumd1883581995-02-15 15:53:08 +00003\stmodindex{shelve}
4\stmodindex{pickle}
5\bimodindex{dbm}
Guido van Rossum470be141995-03-17 16:07:09 +00006\bimodindex{gdbm}
Guido van Rossumd1883581995-02-15 15:53:08 +00007
8A ``shelf'' is a persistent, dictionary-like object. The difference
9with ``dbm'' databases is that the values (not the keys!) in a shelf
10can be essentially arbitrary Python objects --- anything that the
11\code{pickle} module can handle. This includes most class instances,
12recursive data types, and objects containing lots of shared
13sub-objects. The keys are ordinary strings.
14
15To summarize the interface (\code{key} is a string, \code{data} is an
16arbitrary object):
17
Guido van Rossume47da0a1997-07-17 16:34:52 +000018\bcode\begin{verbatim}
Guido van Rossumd1883581995-02-15 15:53:08 +000019import shelve
20
21d = shelve.open(filename) # open, with (g)dbm filename -- no suffix
22
23d[key] = data # store data at key (overwrites old data if
24 # using an existing key)
25data = d[key] # retrieve data at key (raise KeyError if no
26 # such key)
27del d[key] # delete data stored at key (raises KeyError
28 # if no such key)
29flag = d.has_key(key) # true if the key exists
30list = d.keys() # a list of all existing keys (slow!)
31
32d.close() # close it
Guido van Rossume47da0a1997-07-17 16:34:52 +000033\end{verbatim}\ecode
34%
Guido van Rossum5680b951995-02-16 16:29:01 +000035Restrictions:
36
37\begin{itemize}
38
39\item
40The choice of which database package will be used (e.g. dbm or gdbm)
41depends on which interface is available. Therefore it isn't safe to
42open the database directly using dbm. The database is also
43(unfortunately) subject to the limitations of dbm, if it is used ---
44this means that (the pickled representation of) the objects stored in
45the database should be fairly small, and in rare cases key collisions
46may cause the database to refuse updates.
47
48\item
Guido van Rossumd1883581995-02-15 15:53:08 +000049Dependent on the implementation, closing a persistent dictionary may
50or may not be necessary to flush changes to disk.
51
Guido van Rossum5680b951995-02-16 16:29:01 +000052\item
Guido van Rossum470be141995-03-17 16:07:09 +000053The \code{shelve} module does not support {\em concurrent} read/write
54access to shelved objects. (Multiple simultaneous read accesses are
55safe.) When a program has a shelf open for writing, no other program
56should have it open for reading or writing. \UNIX{} file locking can
57be used to solve this, but this differs across \UNIX{} versions and
58requires knowledge about the database implementation used.
Guido van Rossum5680b951995-02-16 16:29:01 +000059
60\end{itemize}