1 \section{Standard Module
\sectcode{shelve
}}
7 A ``shelf'' is a persistent, dictionary-like object. The difference
8 with ``dbm'' databases is that the values (not the keys!) in a shelf
9 can be essentially arbitrary Python objects --- anything that the
10 \code{pickle
} module can handle. This includes most class instances,
11 recursive data types, and objects containing lots of shared
12 sub-objects. The keys are ordinary strings.
14 To summarize the interface (
\code{key
} is a string,
\code{data
} is an
20 d = shelve.open(filename) # open, with (g)dbm filename -- no suffix
22 d
[key
] = data # store data at key (overwrites old data if
23 # using an existing key)
24 data = d
[key
] # retrieve data at key (raise KeyError if no
26 del d
[key
] # delete data stored at key (raises KeyError
28 flag = d.has_key(key) # true if the key exists
29 list = d.keys() # a list of all existing keys (slow!)
39 The choice of which database package will be used (e.g. dbm or gdbm)
40 depends on which interface is available. Therefore it isn't safe to
41 open the database directly using dbm. The database is also
42 (unfortunately) subject to the limitations of dbm, if it is used ---
43 this means that (the pickled representation of) the objects stored in
44 the database should be fairly small, and in rare cases key collisions
45 may cause the database to refuse updates.
48 Dependent on the implementation, closing a persistent dictionary may
49 or may not be necessary to flush changes to disk.
52 The
\code{shelve
} module does not support
{\em concurrent
} read/write
53 access to shelved objects. (Multiple simultaneous read accesses are
54 safe.) When a program has a shelf open for writing, no other program
55 should have it open for reading or writing.
\UNIX{} file locking can
56 be used to solve this, but this differs across
\UNIX{} versions and
57 requires knowledge about the database implementation used.