home *** CD-ROM | disk | FTP | other *** search
/ The Datafile PD-CD 5 / DATAFILE_PDCD5.iso / utilities / p / python / pyhtmldoc / s / shelve < prev    next >
Encoding:
Text File  |  1996-11-14  |  2.4 KB  |  54 lines

  1. <TITLE>shelve -- Python library reference</TITLE>
  2. Next: <A HREF="../c/copy" TYPE="Next">copy</A>  
  3. Prev: <A HREF="../p/pickle" TYPE="Prev">pickle</A>  
  4. Up: <A HREF="../p/python_services" TYPE="Up">Python Services</A>  
  5. Top: <A HREF="../t/top" TYPE="Top">Top</A>  
  6. <H1>3.5. Standard Module <CODE>shelve</CODE></H1>
  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</CODE> 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.
  13. <P>
  14. To summarize the interface (<CODE>key</CODE> is a string, <CODE>data</CODE> is an
  15. arbitrary object):
  16. <P>
  17. <UL COMPACT><CODE>import shelve<P>
  18. <P>
  19. d = shelve.open(filename) # open, with (g)dbm filename -- no suffix<P>
  20. <P>
  21. d[key] = data   # store data at key (overwrites old data if<P>
  22.                 # using an existing key)<P>
  23. data = d[key]   # retrieve data at key (raise KeyError if no<P>
  24.                 # such key)<P>
  25. del d[key]      # delete data stored at key (raises KeyError<P>
  26.                 # if no such key)<P>
  27. flag = d.has_key(key)   # true if the key exists<P>
  28. list = d.keys() # a list of all existing keys (slow!)<P>
  29. <P>
  30. d.close()       # close it<P>
  31. </CODE></UL>
  32. Restrictions:
  33. <P>
  34. <UL>
  35. <LI>•  The choice of which database package will be used (e.g. dbm or gdbm)
  36. depends on which interface is available.  Therefore it isn't safe to
  37. open the database directly using dbm.  The database is also
  38. (unfortunately) subject to the limitations of dbm, if it is used ---
  39. this means that (the pickled representation of) the objects stored in
  40. the database should be fairly small, and in rare cases key collisions
  41. may cause the database to refuse updates.
  42. <P>
  43. <LI>•  Dependent on the implementation, closing a persistent dictionary may
  44. or may not be necessary to flush changes to disk.
  45. <P>
  46. <LI>•  The <CODE>shelve</CODE> module does not support <I>concurrent</I> read/write
  47. access to shelved objects.  (Multiple simultaneous read accesses are
  48. safe.)  When a program has a shelf open for writing, no other program
  49. should have it open for reading or writing.  UNIX file locking can
  50. be used to solve this, but this differs across UNIX versions and
  51. requires knowledge about the database implementation used.
  52. <P>
  53. </UL>
  54.