blob: 3e2bef930371070be8bfb72ea5b93199757998ca [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
33Dependent on the implementation, closing a persistent dictionary may
34or may not be necessary to flush changes to disk.
35
36Note: \code{shelve} does not support {\em concurrent} access to
37shelved objects. Two programs should not try to simultaneously access
38the same shelf.