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