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