home *** CD-ROM | disk | FTP | other *** search
- <TITLE>shelve -- Python library reference</TITLE>
- Next: <A HREF="../c/copy" TYPE="Next">copy</A>
- Prev: <A HREF="../p/pickle" TYPE="Prev">pickle</A>
- Up: <A HREF="../p/python_services" TYPE="Up">Python Services</A>
- Top: <A HREF="../t/top" TYPE="Top">Top</A>
- <H1>3.5. Standard Module <CODE>shelve</CODE></H1>
- A ``shelf'' is a persistent, dictionary-like object. The difference
- with ``dbm'' databases is that the values (not the keys!) in a shelf
- can be essentially arbitrary Python objects --- anything that the
- <CODE>pickle</CODE> module can handle. This includes most class instances,
- recursive data types, and objects containing lots of shared
- sub-objects. The keys are ordinary strings.
- <P>
- To summarize the interface (<CODE>key</CODE> is a string, <CODE>data</CODE> is an
- arbitrary object):
- <P>
- <UL COMPACT><CODE>import shelve<P>
- <P>
- d = shelve.open(filename) # open, with (g)dbm filename -- no suffix<P>
- <P>
- d[key] = data # store data at key (overwrites old data if<P>
- # using an existing key)<P>
- data = d[key] # retrieve data at key (raise KeyError if no<P>
- # such key)<P>
- del d[key] # delete data stored at key (raises KeyError<P>
- # if no such key)<P>
- flag = d.has_key(key) # true if the key exists<P>
- list = d.keys() # a list of all existing keys (slow!)<P>
- <P>
- d.close() # close it<P>
- </CODE></UL>
- Restrictions:
- <P>
- <UL>
- <LI>• The choice of which database package will be used (e.g. dbm or gdbm)
- depends on which interface is available. Therefore it isn't safe to
- open the database directly using dbm. The database is also
- (unfortunately) subject to the limitations of dbm, if it is used ---
- this means that (the pickled representation of) the objects stored in
- the database should be fairly small, and in rare cases key collisions
- may cause the database to refuse updates.
- <P>
- <LI>• Dependent on the implementation, closing a persistent dictionary may
- or may not be necessary to flush changes to disk.
- <P>
- <LI>• The <CODE>shelve</CODE> module does not support <I>concurrent</I> read/write
- access to shelved objects. (Multiple simultaneous read accesses are
- safe.) When a program has a shelf open for writing, no other program
- should have it open for reading or writing. UNIX file locking can
- be used to solve this, but this differs across UNIX versions and
- requires knowledge about the database implementation used.
- <P>
- </UL>
-