PageRenderTime 34ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/breveIDE_2.7.2/lib/python2.4/shelve.py

https://github.com/jpbarbosa/BraitenbergVehicles
Python | 231 lines | 197 code | 0 blank | 34 comment | 1 complexity | 80b8189a6e71b6201192a32e80111c9b MD5 | raw file
  1. """Manage shelves of pickled objects.
  2. A "shelf" is a persistent, dictionary-like object. The difference
  3. with dbm databases is that the values (not the keys!) in a shelf can
  4. be essentially arbitrary Python objects -- anything that the "pickle"
  5. module can handle. This includes most class instances, recursive data
  6. types, and objects containing lots of shared sub-objects. The keys
  7. are ordinary strings.
  8. To summarize the interface (key is a string, data is an arbitrary
  9. object):
  10. import shelve
  11. d = shelve.open(filename) # open, with (g)dbm filename -- no suffix
  12. d[key] = data # store data at key (overwrites old data if
  13. # using an existing key)
  14. data = d[key] # retrieve a COPY of the data at key (raise
  15. # KeyError if no such key) -- NOTE that this
  16. # access returns a *copy* of the entry!
  17. del d[key] # delete data stored at key (raises KeyError
  18. # if no such key)
  19. flag = d.has_key(key) # true if the key exists; same as "key in d"
  20. list = d.keys() # a list of all existing keys (slow!)
  21. d.close() # close it
  22. Dependent on the implementation, closing a persistent dictionary may
  23. or may not be necessary to flush changes to disk.
  24. Normally, d[key] returns a COPY of the entry. This needs care when
  25. mutable entries are mutated: for example, if d[key] is a list,
  26. d[key].append(anitem)
  27. does NOT modify the entry d[key] itself, as stored in the persistent
  28. mapping -- it only modifies the copy, which is then immediately
  29. discarded, so that the append has NO effect whatsoever. To append an
  30. item to d[key] in a way that will affect the persistent mapping, use:
  31. data = d[key]
  32. data.append(anitem)
  33. d[key] = data
  34. To avoid the problem with mutable entries, you may pass the keyword
  35. argument writeback=True in the call to shelve.open. When you use:
  36. d = shelve.open(filename, writeback=True)
  37. then d keeps a cache of all entries you access, and writes them all back
  38. to the persistent mapping when you call d.close(). This ensures that
  39. such usage as d[key].append(anitem) works as intended.
  40. However, using keyword argument writeback=True may consume vast amount
  41. of memory for the cache, and it may make d.close() very slow, if you
  42. access many of d's entries after opening it in this way: d has no way to
  43. check which of the entries you access are mutable and/or which ones you
  44. actually mutate, so it must cache, and write back at close, all of the
  45. entries that you access. You can call d.sync() to write back all the
  46. entries in the cache, and empty the cache (d.sync() also synchronizes
  47. the persistent dictionary on disk, if feasible).
  48. """
  49. # Try using cPickle and cStringIO if available.
  50. try:
  51. from cPickle import Pickler, Unpickler
  52. except ImportError:
  53. from pickle import Pickler, Unpickler
  54. try:
  55. from cStringIO import StringIO
  56. except ImportError:
  57. from StringIO import StringIO
  58. import UserDict
  59. import warnings
  60. __all__ = ["Shelf","BsdDbShelf","DbfilenameShelf","open"]
  61. class Shelf(UserDict.DictMixin):
  62. """Base class for shelf implementations.
  63. This is initialized with a dictionary-like object.
  64. See the module's __doc__ string for an overview of the interface.
  65. """
  66. def __init__(self, dict, protocol=None, writeback=False, binary=None):
  67. self.dict = dict
  68. if protocol is not None and binary is not None:
  69. raise ValueError, "can't specify both 'protocol' and 'binary'"
  70. if binary is not None:
  71. warnings.warn("The 'binary' argument to Shelf() is deprecated",
  72. PendingDeprecationWarning)
  73. protocol = int(binary)
  74. if protocol is None:
  75. protocol = 0
  76. self._protocol = protocol
  77. self.writeback = writeback
  78. self.cache = {}
  79. def keys(self):
  80. return self.dict.keys()
  81. def __len__(self):
  82. return len(self.dict)
  83. def has_key(self, key):
  84. return self.dict.has_key(key)
  85. def __contains__(self, key):
  86. return self.dict.has_key(key)
  87. def get(self, key, default=None):
  88. if self.dict.has_key(key):
  89. return self[key]
  90. return default
  91. def __getitem__(self, key):
  92. try:
  93. value = self.cache[key]
  94. except KeyError:
  95. f = StringIO(self.dict[key])
  96. value = Unpickler(f).load()
  97. if self.writeback:
  98. self.cache[key] = value
  99. return value
  100. def __setitem__(self, key, value):
  101. if self.writeback:
  102. self.cache[key] = value
  103. f = StringIO()
  104. p = Pickler(f, self._protocol)
  105. p.dump(value)
  106. self.dict[key] = f.getvalue()
  107. def __delitem__(self, key):
  108. del self.dict[key]
  109. try:
  110. del self.cache[key]
  111. except KeyError:
  112. pass
  113. def close(self):
  114. self.sync()
  115. try:
  116. self.dict.close()
  117. except AttributeError:
  118. pass
  119. self.dict = 0
  120. def __del__(self):
  121. self.close()
  122. def sync(self):
  123. if self.writeback and self.cache:
  124. self.writeback = False
  125. for key, entry in self.cache.iteritems():
  126. self[key] = entry
  127. self.writeback = True
  128. self.cache = {}
  129. if hasattr(self.dict, 'sync'):
  130. self.dict.sync()
  131. class BsdDbShelf(Shelf):
  132. """Shelf implementation using the "BSD" db interface.
  133. This adds methods first(), next(), previous(), last() and
  134. set_location() that have no counterpart in [g]dbm databases.
  135. The actual database must be opened using one of the "bsddb"
  136. modules "open" routines (i.e. bsddb.hashopen, bsddb.btopen or
  137. bsddb.rnopen) and passed to the constructor.
  138. See the module's __doc__ string for an overview of the interface.
  139. """
  140. def __init__(self, dict, protocol=None, writeback=False, binary=None):
  141. Shelf.__init__(self, dict, protocol, writeback, binary)
  142. def set_location(self, key):
  143. (key, value) = self.dict.set_location(key)
  144. f = StringIO(value)
  145. return (key, Unpickler(f).load())
  146. def next(self):
  147. (key, value) = self.dict.next()
  148. f = StringIO(value)
  149. return (key, Unpickler(f).load())
  150. def previous(self):
  151. (key, value) = self.dict.previous()
  152. f = StringIO(value)
  153. return (key, Unpickler(f).load())
  154. def first(self):
  155. (key, value) = self.dict.first()
  156. f = StringIO(value)
  157. return (key, Unpickler(f).load())
  158. def last(self):
  159. (key, value) = self.dict.last()
  160. f = StringIO(value)
  161. return (key, Unpickler(f).load())
  162. class DbfilenameShelf(Shelf):
  163. """Shelf implementation using the "anydbm" generic dbm interface.
  164. This is initialized with the filename for the dbm database.
  165. See the module's __doc__ string for an overview of the interface.
  166. """
  167. def __init__(self, filename, flag='c', protocol=None, writeback=False, binary=None):
  168. import anydbm
  169. Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback, binary)
  170. def open(filename, flag='c', protocol=None, writeback=False, binary=None):
  171. """Open a persistent dictionary for reading and writing.
  172. The filename parameter is the base filename for the underlying
  173. database. As a side-effect, an extension may be added to the
  174. filename and more than one file may be created. The optional flag
  175. parameter has the same interpretation as the flag parameter of
  176. anydbm.open(). The optional protocol parameter specifies the
  177. version of the pickle protocol (0, 1, or 2).
  178. The optional binary parameter is deprecated and may be set to True
  179. to force the use of binary pickles for serializing data values.
  180. See the module's __doc__ string for an overview of the interface.
  181. """
  182. return DbfilenameShelf(filename, flag, protocol, writeback, binary)