| Guido van Rossum | cc6764c | 1995-02-09 17:18:10 +0000 | [diff] [blame] | 1 | """Manage shelves of pickled objects. | 
 | 2 |  | 
 | 3 | A "shelf" is a persistent, dictionary-like object.  The difference | 
 | 4 | with dbm databases is that the values (not the keys!) in a shelf can | 
 | 5 | be essentially arbitrary Python objects -- anything that the "pickle" | 
 | 6 | module can handle.  This includes most class instances, recursive data | 
 | 7 | types, and objects containing lots of shared sub-objects.  The keys | 
 | 8 | are ordinary strings. | 
 | 9 |  | 
 | 10 | To summarize the interface (key is a string, data is an arbitrary | 
 | 11 | object): | 
 | 12 |  | 
| Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 13 |         import shelve | 
 | 14 |         d = shelve.open(filename) # open, with (g)dbm filename -- no suffix | 
| Guido van Rossum | cc6764c | 1995-02-09 17:18:10 +0000 | [diff] [blame] | 15 |  | 
| Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 16 |         d[key] = data   # store data at key (overwrites old data if | 
 | 17 |                         # using an existing key) | 
| Tim Peters | 0eadaac | 2003-04-24 16:02:54 +0000 | [diff] [blame] | 18 |         data = d[key]   # retrieve a COPY of the data at key (raise | 
| Martin v. Löwis | 153c9e4 | 2003-04-19 20:59:03 +0000 | [diff] [blame] | 19 |                         # KeyError if no such key) -- NOTE that this | 
 | 20 |                         # access returns a *copy* of the entry! | 
| Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 21 |         del d[key]      # delete data stored at key (raises KeyError | 
 | 22 |                         # if no such key) | 
| Martin v. Löwis | e4913c9 | 2002-10-18 08:58:14 +0000 | [diff] [blame] | 23 |         flag = d.has_key(key)   # true if the key exists; same as "key in d" | 
| Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 24 |         list = d.keys() # a list of all existing keys (slow!) | 
| Guido van Rossum | cc6764c | 1995-02-09 17:18:10 +0000 | [diff] [blame] | 25 |  | 
| Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 26 |         d.close()       # close it | 
| Guido van Rossum | cc6764c | 1995-02-09 17:18:10 +0000 | [diff] [blame] | 27 |  | 
 | 28 | Dependent on the implementation, closing a persistent dictionary may | 
 | 29 | or may not be necessary to flush changes to disk. | 
| Martin v. Löwis | 153c9e4 | 2003-04-19 20:59:03 +0000 | [diff] [blame] | 30 |  | 
 | 31 | Normally, d[key] returns a COPY of the entry.  This needs care when | 
 | 32 | mutable entries are mutated: for example, if d[key] is a list, | 
 | 33 |         d[key].append(anitem) | 
 | 34 | does NOT modify the entry d[key] itself, as stored in the persistent | 
 | 35 | mapping -- it only modifies the copy, which is then immediately | 
 | 36 | discarded, so that the append has NO effect whatsoever.  To append an | 
 | 37 | item to d[key] in a way that will affect the persistent mapping, use: | 
 | 38 |         data = d[key] | 
 | 39 |         data.append(anitem) | 
 | 40 |         d[key] = data | 
 | 41 |  | 
 | 42 | To avoid the problem with mutable entries, you may pass the keyword | 
 | 43 | argument writeback=True in the call to shelve.open.  When you use: | 
 | 44 |         d = shelve.open(filename, writeback=True) | 
 | 45 | then d keeps a cache of all entries you access, and writes them all back | 
 | 46 | to the persistent mapping when you call d.close().  This ensures that | 
 | 47 | such usage as d[key].append(anitem) works as intended. | 
 | 48 |  | 
 | 49 | However, using keyword argument writeback=True may consume vast amount | 
 | 50 | of memory for the cache, and it may make d.close() very slow, if you | 
 | 51 | access many of d's entries after opening it in this way: d has no way to | 
 | 52 | check which of the entries you access are mutable and/or which ones you | 
 | 53 | actually mutate, so it must cache, and write back at close, all of the | 
 | 54 | entries that you access.  You can call d.sync() to write back all the | 
 | 55 | entries in the cache, and empty the cache (d.sync() also synchronizes | 
 | 56 | the persistent dictionary on disk, if feasible). | 
| Guido van Rossum | cc6764c | 1995-02-09 17:18:10 +0000 | [diff] [blame] | 57 | """ | 
| Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 58 |  | 
| Guido van Rossum | 914c938 | 1997-06-06 21:12:45 +0000 | [diff] [blame] | 59 | # Try using cPickle and cStringIO if available. | 
 | 60 |  | 
 | 61 | try: | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 62 |     from cPickle import Pickler, Unpickler | 
| Guido van Rossum | 914c938 | 1997-06-06 21:12:45 +0000 | [diff] [blame] | 63 | except ImportError: | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 64 |     from pickle import Pickler, Unpickler | 
| Guido van Rossum | 914c938 | 1997-06-06 21:12:45 +0000 | [diff] [blame] | 65 |  | 
 | 66 | try: | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 67 |     from cStringIO import StringIO | 
| Guido van Rossum | 914c938 | 1997-06-06 21:12:45 +0000 | [diff] [blame] | 68 | except ImportError: | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 69 |     from StringIO import StringIO | 
| Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 70 |  | 
| Raymond Hettinger | 7994716 | 2002-11-15 06:46:14 +0000 | [diff] [blame] | 71 | import UserDict | 
 | 72 |  | 
| Skip Montanaro | 0de6580 | 2001-02-15 22:15:14 +0000 | [diff] [blame] | 73 | __all__ = ["Shelf","BsdDbShelf","DbfilenameShelf","open"] | 
| Guido van Rossum | cc6764c | 1995-02-09 17:18:10 +0000 | [diff] [blame] | 74 |  | 
| Raymond Hettinger | 8c664e8 | 2008-07-25 18:43:33 +0000 | [diff] [blame] | 75 | class _ClosedDict(UserDict.DictMixin): | 
 | 76 |     'Marker for a closed dict.  Access attempts raise a ValueError.' | 
 | 77 |  | 
 | 78 |     def closed(self, *args): | 
 | 79 |         raise ValueError('invalid operation on closed shelf') | 
 | 80 |     __getitem__ = __setitem__ = __delitem__ = keys = closed | 
 | 81 |  | 
 | 82 |     def __repr__(self): | 
 | 83 |         return '<Closed Dictionary>' | 
 | 84 |  | 
| Raymond Hettinger | 7994716 | 2002-11-15 06:46:14 +0000 | [diff] [blame] | 85 | class Shelf(UserDict.DictMixin): | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 86 |     """Base class for shelf implementations. | 
| Guido van Rossum | cc6764c | 1995-02-09 17:18:10 +0000 | [diff] [blame] | 87 |  | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 88 |     This is initialized with a dictionary-like object. | 
 | 89 |     See the module's __doc__ string for an overview of the interface. | 
 | 90 |     """ | 
| Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 91 |  | 
| Raymond Hettinger | 1bc82f8 | 2004-12-05 03:58:17 +0000 | [diff] [blame] | 92 |     def __init__(self, dict, protocol=None, writeback=False): | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 93 |         self.dict = dict | 
| Martin v. Löwis | 153c9e4 | 2003-04-19 20:59:03 +0000 | [diff] [blame] | 94 |         if protocol is None: | 
 | 95 |             protocol = 0 | 
 | 96 |         self._protocol = protocol | 
 | 97 |         self.writeback = writeback | 
 | 98 |         self.cache = {} | 
| Guido van Rossum | 2f7df12 | 1999-08-11 01:54:05 +0000 | [diff] [blame] | 99 |  | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 100 |     def keys(self): | 
 | 101 |         return self.dict.keys() | 
| Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 102 |  | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 103 |     def __len__(self): | 
 | 104 |         return len(self.dict) | 
| Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 105 |  | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 106 |     def has_key(self, key): | 
| Brett Cannon | 753ecb1 | 2008-08-04 21:17:15 +0000 | [diff] [blame] | 107 |         return key in self.dict | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 108 |  | 
| Martin v. Löwis | e4913c9 | 2002-10-18 08:58:14 +0000 | [diff] [blame] | 109 |     def __contains__(self, key): | 
| Brett Cannon | 753ecb1 | 2008-08-04 21:17:15 +0000 | [diff] [blame] | 110 |         return key in self.dict | 
| Martin v. Löwis | e4913c9 | 2002-10-18 08:58:14 +0000 | [diff] [blame] | 111 |  | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 112 |     def get(self, key, default=None): | 
| Brett Cannon | 753ecb1 | 2008-08-04 21:17:15 +0000 | [diff] [blame] | 113 |         if key in self.dict: | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 114 |             return self[key] | 
 | 115 |         return default | 
 | 116 |  | 
 | 117 |     def __getitem__(self, key): | 
| Martin v. Löwis | 153c9e4 | 2003-04-19 20:59:03 +0000 | [diff] [blame] | 118 |         try: | 
 | 119 |             value = self.cache[key] | 
 | 120 |         except KeyError: | 
 | 121 |             f = StringIO(self.dict[key]) | 
 | 122 |             value = Unpickler(f).load() | 
 | 123 |             if self.writeback: | 
 | 124 |                 self.cache[key] = value | 
 | 125 |         return value | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 126 |  | 
 | 127 |     def __setitem__(self, key, value): | 
| Martin v. Löwis | 153c9e4 | 2003-04-19 20:59:03 +0000 | [diff] [blame] | 128 |         if self.writeback: | 
 | 129 |             self.cache[key] = value | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 130 |         f = StringIO() | 
| Martin v. Löwis | 153c9e4 | 2003-04-19 20:59:03 +0000 | [diff] [blame] | 131 |         p = Pickler(f, self._protocol) | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 132 |         p.dump(value) | 
 | 133 |         self.dict[key] = f.getvalue() | 
 | 134 |  | 
 | 135 |     def __delitem__(self, key): | 
 | 136 |         del self.dict[key] | 
| Martin v. Löwis | 153c9e4 | 2003-04-19 20:59:03 +0000 | [diff] [blame] | 137 |         try: | 
 | 138 |             del self.cache[key] | 
 | 139 |         except KeyError: | 
 | 140 |             pass | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 141 |  | 
 | 142 |     def close(self): | 
| Martin v. Löwis | 153c9e4 | 2003-04-19 20:59:03 +0000 | [diff] [blame] | 143 |         self.sync() | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 144 |         try: | 
 | 145 |             self.dict.close() | 
| Raymond Hettinger | 68dcd34 | 2003-05-27 06:30:52 +0000 | [diff] [blame] | 146 |         except AttributeError: | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 147 |             pass | 
| R. David Murray | 031ae6e | 2010-02-11 01:56:42 +0000 | [diff] [blame] | 148 |         # Catch errors that may happen when close is called from __del__ | 
 | 149 |         # because CPython is in interpreter shutdown. | 
 | 150 |         try: | 
| R. David Murray | 63e4fd7 | 2010-02-10 22:42:04 +0000 | [diff] [blame] | 151 |             self.dict = _ClosedDict() | 
| R. David Murray | 031ae6e | 2010-02-11 01:56:42 +0000 | [diff] [blame] | 152 |         except (NameError, TypeError): | 
 | 153 |             self.dict = None | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 154 |  | 
 | 155 |     def __del__(self): | 
| Georg Brandl | 2605ca8 | 2006-06-14 06:08:31 +0000 | [diff] [blame] | 156 |         if not hasattr(self, 'writeback'): | 
 | 157 |             # __init__ didn't succeed, so don't bother closing | 
 | 158 |             return | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 159 |         self.close() | 
 | 160 |  | 
 | 161 |     def sync(self): | 
| Martin v. Löwis | 153c9e4 | 2003-04-19 20:59:03 +0000 | [diff] [blame] | 162 |         if self.writeback and self.cache: | 
 | 163 |             self.writeback = False | 
 | 164 |             for key, entry in self.cache.iteritems(): | 
 | 165 |                 self[key] = entry | 
 | 166 |             self.writeback = True | 
 | 167 |             self.cache = {} | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 168 |         if hasattr(self.dict, 'sync'): | 
 | 169 |             self.dict.sync() | 
 | 170 |  | 
| Guido van Rossum | cc6764c | 1995-02-09 17:18:10 +0000 | [diff] [blame] | 171 |  | 
| Guido van Rossum | abad1cc | 1995-08-11 14:19:16 +0000 | [diff] [blame] | 172 | class BsdDbShelf(Shelf): | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 173 |     """Shelf implementation using the "BSD" db interface. | 
| Guido van Rossum | abad1cc | 1995-08-11 14:19:16 +0000 | [diff] [blame] | 174 |  | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 175 |     This adds methods first(), next(), previous(), last() and | 
 | 176 |     set_location() that have no counterpart in [g]dbm databases. | 
| Guido van Rossum | abad1cc | 1995-08-11 14:19:16 +0000 | [diff] [blame] | 177 |  | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 178 |     The actual database must be opened using one of the "bsddb" | 
 | 179 |     modules "open" routines (i.e. bsddb.hashopen, bsddb.btopen or | 
 | 180 |     bsddb.rnopen) and passed to the constructor. | 
| Guido van Rossum | abad1cc | 1995-08-11 14:19:16 +0000 | [diff] [blame] | 181 |  | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 182 |     See the module's __doc__ string for an overview of the interface. | 
 | 183 |     """ | 
| Guido van Rossum | abad1cc | 1995-08-11 14:19:16 +0000 | [diff] [blame] | 184 |  | 
| Raymond Hettinger | 1bc82f8 | 2004-12-05 03:58:17 +0000 | [diff] [blame] | 185 |     def __init__(self, dict, protocol=None, writeback=False): | 
 | 186 |         Shelf.__init__(self, dict, protocol, writeback) | 
| Guido van Rossum | abad1cc | 1995-08-11 14:19:16 +0000 | [diff] [blame] | 187 |  | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 188 |     def set_location(self, key): | 
 | 189 |         (key, value) = self.dict.set_location(key) | 
 | 190 |         f = StringIO(value) | 
 | 191 |         return (key, Unpickler(f).load()) | 
| Guido van Rossum | abad1cc | 1995-08-11 14:19:16 +0000 | [diff] [blame] | 192 |  | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 193 |     def next(self): | 
 | 194 |         (key, value) = self.dict.next() | 
 | 195 |         f = StringIO(value) | 
 | 196 |         return (key, Unpickler(f).load()) | 
| Guido van Rossum | abad1cc | 1995-08-11 14:19:16 +0000 | [diff] [blame] | 197 |  | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 198 |     def previous(self): | 
 | 199 |         (key, value) = self.dict.previous() | 
 | 200 |         f = StringIO(value) | 
 | 201 |         return (key, Unpickler(f).load()) | 
| Guido van Rossum | abad1cc | 1995-08-11 14:19:16 +0000 | [diff] [blame] | 202 |  | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 203 |     def first(self): | 
 | 204 |         (key, value) = self.dict.first() | 
 | 205 |         f = StringIO(value) | 
 | 206 |         return (key, Unpickler(f).load()) | 
| Guido van Rossum | abad1cc | 1995-08-11 14:19:16 +0000 | [diff] [blame] | 207 |  | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 208 |     def last(self): | 
 | 209 |         (key, value) = self.dict.last() | 
 | 210 |         f = StringIO(value) | 
 | 211 |         return (key, Unpickler(f).load()) | 
| Guido van Rossum | abad1cc | 1995-08-11 14:19:16 +0000 | [diff] [blame] | 212 |  | 
 | 213 |  | 
 | 214 | class DbfilenameShelf(Shelf): | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 215 |     """Shelf implementation using the "anydbm" generic dbm interface. | 
| Guido van Rossum | cc6764c | 1995-02-09 17:18:10 +0000 | [diff] [blame] | 216 |  | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 217 |     This is initialized with the filename for the dbm database. | 
 | 218 |     See the module's __doc__ string for an overview of the interface. | 
 | 219 |     """ | 
 | 220 |  | 
| Raymond Hettinger | 1bc82f8 | 2004-12-05 03:58:17 +0000 | [diff] [blame] | 221 |     def __init__(self, filename, flag='c', protocol=None, writeback=False): | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 222 |         import anydbm | 
| Raymond Hettinger | 1bc82f8 | 2004-12-05 03:58:17 +0000 | [diff] [blame] | 223 |         Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback) | 
| Guido van Rossum | cc6764c | 1995-02-09 17:18:10 +0000 | [diff] [blame] | 224 |  | 
 | 225 |  | 
| Raymond Hettinger | 1bc82f8 | 2004-12-05 03:58:17 +0000 | [diff] [blame] | 226 | def open(filename, flag='c', protocol=None, writeback=False): | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 227 |     """Open a persistent dictionary for reading and writing. | 
| Guido van Rossum | cc6764c | 1995-02-09 17:18:10 +0000 | [diff] [blame] | 228 |  | 
| Martin v. Löwis | 153c9e4 | 2003-04-19 20:59:03 +0000 | [diff] [blame] | 229 |     The filename parameter is the base filename for the underlying | 
 | 230 |     database.  As a side-effect, an extension may be added to the | 
 | 231 |     filename and more than one file may be created.  The optional flag | 
 | 232 |     parameter has the same interpretation as the flag parameter of | 
 | 233 |     anydbm.open(). The optional protocol parameter specifies the | 
 | 234 |     version of the pickle protocol (0, 1, or 2). | 
 | 235 |  | 
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 236 |     See the module's __doc__ string for an overview of the interface. | 
 | 237 |     """ | 
 | 238 |  | 
| Raymond Hettinger | 1bc82f8 | 2004-12-05 03:58:17 +0000 | [diff] [blame] | 239 |     return DbfilenameShelf(filename, flag, protocol, writeback) |