blob: 1f78fc17fd3c745b78b15f5a934ec680e38e6561 [file] [log] [blame]
Guido van Rossumcc6764c1995-02-09 17:18:10 +00001"""Manage shelves of pickled objects.
2
3A "shelf" is a persistent, dictionary-like object. The difference
4with dbm databases is that the values (not the keys!) in a shelf can
5be essentially arbitrary Python objects -- anything that the "pickle"
6module can handle. This includes most class instances, recursive data
7types, and objects containing lots of shared sub-objects. The keys
8are ordinary strings.
9
10To summarize the interface (key is a string, data is an arbitrary
11object):
12
Fred Drake13a2c272000-02-10 17:17:14 +000013 import shelve
14 d = shelve.open(filename) # open, with (g)dbm filename -- no suffix
Guido van Rossumcc6764c1995-02-09 17:18:10 +000015
Fred Drake13a2c272000-02-10 17:17:14 +000016 d[key] = data # store data at key (overwrites old data if
17 # using an existing key)
Tim Peters0eadaac2003-04-24 16:02:54 +000018 data = d[key] # retrieve a COPY of the data at key (raise
Martin v. Löwis153c9e42003-04-19 20:59:03 +000019 # KeyError if no such key) -- NOTE that this
20 # access returns a *copy* of the entry!
Fred Drake13a2c272000-02-10 17:17:14 +000021 del d[key] # delete data stored at key (raises KeyError
22 # if no such key)
Martin v. Löwise4913c92002-10-18 08:58:14 +000023 flag = d.has_key(key) # true if the key exists; same as "key in d"
Fred Drake13a2c272000-02-10 17:17:14 +000024 list = d.keys() # a list of all existing keys (slow!)
Guido van Rossumcc6764c1995-02-09 17:18:10 +000025
Fred Drake13a2c272000-02-10 17:17:14 +000026 d.close() # close it
Guido van Rossumcc6764c1995-02-09 17:18:10 +000027
28Dependent on the implementation, closing a persistent dictionary may
29or may not be necessary to flush changes to disk.
Martin v. Löwis153c9e42003-04-19 20:59:03 +000030
31Normally, d[key] returns a COPY of the entry. This needs care when
32mutable entries are mutated: for example, if d[key] is a list,
33 d[key].append(anitem)
34does NOT modify the entry d[key] itself, as stored in the persistent
35mapping -- it only modifies the copy, which is then immediately
36discarded, so that the append has NO effect whatsoever. To append an
37item 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
42To avoid the problem with mutable entries, you may pass the keyword
43argument writeback=True in the call to shelve.open. When you use:
44 d = shelve.open(filename, writeback=True)
45then d keeps a cache of all entries you access, and writes them all back
46to the persistent mapping when you call d.close(). This ensures that
47such usage as d[key].append(anitem) works as intended.
48
49However, using keyword argument writeback=True may consume vast amount
50of memory for the cache, and it may make d.close() very slow, if you
51access many of d's entries after opening it in this way: d has no way to
52check which of the entries you access are mutable and/or which ones you
53actually mutate, so it must cache, and write back at close, all of the
54entries that you access. You can call d.sync() to write back all the
55entries in the cache, and empty the cache (d.sync() also synchronizes
56the persistent dictionary on disk, if feasible).
Guido van Rossumcc6764c1995-02-09 17:18:10 +000057"""
Guido van Rossuma48061a1995-01-10 00:31:14 +000058
Guido van Rossum914c9381997-06-06 21:12:45 +000059# Try using cPickle and cStringIO if available.
60
61try:
Tim Peters495ad3c2001-01-15 01:36:40 +000062 from cPickle import Pickler, Unpickler
Guido van Rossum914c9381997-06-06 21:12:45 +000063except ImportError:
Tim Peters495ad3c2001-01-15 01:36:40 +000064 from pickle import Pickler, Unpickler
Guido van Rossum914c9381997-06-06 21:12:45 +000065
66try:
Tim Peters495ad3c2001-01-15 01:36:40 +000067 from cStringIO import StringIO
Guido van Rossum914c9381997-06-06 21:12:45 +000068except ImportError:
Tim Peters495ad3c2001-01-15 01:36:40 +000069 from StringIO import StringIO
Guido van Rossuma48061a1995-01-10 00:31:14 +000070
Raymond Hettinger79947162002-11-15 06:46:14 +000071import UserDict
Martin v. Löwis153c9e42003-04-19 20:59:03 +000072import warnings
Raymond Hettinger79947162002-11-15 06:46:14 +000073
Skip Montanaro0de65802001-02-15 22:15:14 +000074__all__ = ["Shelf","BsdDbShelf","DbfilenameShelf","open"]
Guido van Rossumcc6764c1995-02-09 17:18:10 +000075
Raymond Hettinger8c664e82008-07-25 18:43:33 +000076class _ClosedDict(UserDict.DictMixin):
77 'Marker for a closed dict. Access attempts raise a ValueError.'
78
79 def closed(self, *args):
80 raise ValueError('invalid operation on closed shelf')
81 __getitem__ = __setitem__ = __delitem__ = keys = closed
82
83 def __repr__(self):
84 return '<Closed Dictionary>'
85
Raymond Hettinger79947162002-11-15 06:46:14 +000086class Shelf(UserDict.DictMixin):
Tim Peters495ad3c2001-01-15 01:36:40 +000087 """Base class for shelf implementations.
Guido van Rossumcc6764c1995-02-09 17:18:10 +000088
Tim Peters495ad3c2001-01-15 01:36:40 +000089 This is initialized with a dictionary-like object.
90 See the module's __doc__ string for an overview of the interface.
91 """
Guido van Rossuma48061a1995-01-10 00:31:14 +000092
Raymond Hettinger1bc82f82004-12-05 03:58:17 +000093 def __init__(self, dict, protocol=None, writeback=False):
Tim Peters495ad3c2001-01-15 01:36:40 +000094 self.dict = dict
Martin v. Löwis153c9e42003-04-19 20:59:03 +000095 if protocol is None:
96 protocol = 0
97 self._protocol = protocol
98 self.writeback = writeback
99 self.cache = {}
Guido van Rossum2f7df121999-08-11 01:54:05 +0000100
Tim Peters495ad3c2001-01-15 01:36:40 +0000101 def keys(self):
102 return self.dict.keys()
Guido van Rossuma48061a1995-01-10 00:31:14 +0000103
Tim Peters495ad3c2001-01-15 01:36:40 +0000104 def __len__(self):
105 return len(self.dict)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000106
Tim Peters495ad3c2001-01-15 01:36:40 +0000107 def has_key(self, key):
Brett Cannon753ecb12008-08-04 21:17:15 +0000108 return key in self.dict
Tim Peters495ad3c2001-01-15 01:36:40 +0000109
Martin v. Löwise4913c92002-10-18 08:58:14 +0000110 def __contains__(self, key):
Brett Cannon753ecb12008-08-04 21:17:15 +0000111 return key in self.dict
Martin v. Löwise4913c92002-10-18 08:58:14 +0000112
Tim Peters495ad3c2001-01-15 01:36:40 +0000113 def get(self, key, default=None):
Brett Cannon753ecb12008-08-04 21:17:15 +0000114 if key in self.dict:
Tim Peters495ad3c2001-01-15 01:36:40 +0000115 return self[key]
116 return default
117
118 def __getitem__(self, key):
Martin v. Löwis153c9e42003-04-19 20:59:03 +0000119 try:
120 value = self.cache[key]
121 except KeyError:
122 f = StringIO(self.dict[key])
123 value = Unpickler(f).load()
124 if self.writeback:
125 self.cache[key] = value
126 return value
Tim Peters495ad3c2001-01-15 01:36:40 +0000127
128 def __setitem__(self, key, value):
Martin v. Löwis153c9e42003-04-19 20:59:03 +0000129 if self.writeback:
130 self.cache[key] = value
Tim Peters495ad3c2001-01-15 01:36:40 +0000131 f = StringIO()
Martin v. Löwis153c9e42003-04-19 20:59:03 +0000132 p = Pickler(f, self._protocol)
Tim Peters495ad3c2001-01-15 01:36:40 +0000133 p.dump(value)
134 self.dict[key] = f.getvalue()
135
136 def __delitem__(self, key):
137 del self.dict[key]
Martin v. Löwis153c9e42003-04-19 20:59:03 +0000138 try:
139 del self.cache[key]
140 except KeyError:
141 pass
Tim Peters495ad3c2001-01-15 01:36:40 +0000142
143 def close(self):
Martin v. Löwis153c9e42003-04-19 20:59:03 +0000144 self.sync()
Tim Peters495ad3c2001-01-15 01:36:40 +0000145 try:
146 self.dict.close()
Raymond Hettinger68dcd342003-05-27 06:30:52 +0000147 except AttributeError:
Tim Peters495ad3c2001-01-15 01:36:40 +0000148 pass
Raymond Hettinger8c664e82008-07-25 18:43:33 +0000149 self.dict = _ClosedDict()
Tim Peters495ad3c2001-01-15 01:36:40 +0000150
151 def __del__(self):
Georg Brandl2605ca82006-06-14 06:08:31 +0000152 if not hasattr(self, 'writeback'):
153 # __init__ didn't succeed, so don't bother closing
154 return
Tim Peters495ad3c2001-01-15 01:36:40 +0000155 self.close()
156
157 def sync(self):
Martin v. Löwis153c9e42003-04-19 20:59:03 +0000158 if self.writeback and self.cache:
159 self.writeback = False
160 for key, entry in self.cache.iteritems():
161 self[key] = entry
162 self.writeback = True
163 self.cache = {}
Tim Peters495ad3c2001-01-15 01:36:40 +0000164 if hasattr(self.dict, 'sync'):
165 self.dict.sync()
166
Guido van Rossumcc6764c1995-02-09 17:18:10 +0000167
Guido van Rossumabad1cc1995-08-11 14:19:16 +0000168class BsdDbShelf(Shelf):
Tim Peters495ad3c2001-01-15 01:36:40 +0000169 """Shelf implementation using the "BSD" db interface.
Guido van Rossumabad1cc1995-08-11 14:19:16 +0000170
Tim Peters495ad3c2001-01-15 01:36:40 +0000171 This adds methods first(), next(), previous(), last() and
172 set_location() that have no counterpart in [g]dbm databases.
Guido van Rossumabad1cc1995-08-11 14:19:16 +0000173
Tim Peters495ad3c2001-01-15 01:36:40 +0000174 The actual database must be opened using one of the "bsddb"
175 modules "open" routines (i.e. bsddb.hashopen, bsddb.btopen or
176 bsddb.rnopen) and passed to the constructor.
Guido van Rossumabad1cc1995-08-11 14:19:16 +0000177
Tim Peters495ad3c2001-01-15 01:36:40 +0000178 See the module's __doc__ string for an overview of the interface.
179 """
Guido van Rossumabad1cc1995-08-11 14:19:16 +0000180
Raymond Hettinger1bc82f82004-12-05 03:58:17 +0000181 def __init__(self, dict, protocol=None, writeback=False):
182 Shelf.__init__(self, dict, protocol, writeback)
Guido van Rossumabad1cc1995-08-11 14:19:16 +0000183
Tim Peters495ad3c2001-01-15 01:36:40 +0000184 def set_location(self, key):
185 (key, value) = self.dict.set_location(key)
186 f = StringIO(value)
187 return (key, Unpickler(f).load())
Guido van Rossumabad1cc1995-08-11 14:19:16 +0000188
Tim Peters495ad3c2001-01-15 01:36:40 +0000189 def next(self):
190 (key, value) = self.dict.next()
191 f = StringIO(value)
192 return (key, Unpickler(f).load())
Guido van Rossumabad1cc1995-08-11 14:19:16 +0000193
Tim Peters495ad3c2001-01-15 01:36:40 +0000194 def previous(self):
195 (key, value) = self.dict.previous()
196 f = StringIO(value)
197 return (key, Unpickler(f).load())
Guido van Rossumabad1cc1995-08-11 14:19:16 +0000198
Tim Peters495ad3c2001-01-15 01:36:40 +0000199 def first(self):
200 (key, value) = self.dict.first()
201 f = StringIO(value)
202 return (key, Unpickler(f).load())
Guido van Rossumabad1cc1995-08-11 14:19:16 +0000203
Tim Peters495ad3c2001-01-15 01:36:40 +0000204 def last(self):
205 (key, value) = self.dict.last()
206 f = StringIO(value)
207 return (key, Unpickler(f).load())
Guido van Rossumabad1cc1995-08-11 14:19:16 +0000208
209
210class DbfilenameShelf(Shelf):
Tim Peters495ad3c2001-01-15 01:36:40 +0000211 """Shelf implementation using the "anydbm" generic dbm interface.
Guido van Rossumcc6764c1995-02-09 17:18:10 +0000212
Tim Peters495ad3c2001-01-15 01:36:40 +0000213 This is initialized with the filename for the dbm database.
214 See the module's __doc__ string for an overview of the interface.
215 """
216
Raymond Hettinger1bc82f82004-12-05 03:58:17 +0000217 def __init__(self, filename, flag='c', protocol=None, writeback=False):
Tim Peters495ad3c2001-01-15 01:36:40 +0000218 import anydbm
Raymond Hettinger1bc82f82004-12-05 03:58:17 +0000219 Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback)
Guido van Rossumcc6764c1995-02-09 17:18:10 +0000220
221
Raymond Hettinger1bc82f82004-12-05 03:58:17 +0000222def open(filename, flag='c', protocol=None, writeback=False):
Tim Peters495ad3c2001-01-15 01:36:40 +0000223 """Open a persistent dictionary for reading and writing.
Guido van Rossumcc6764c1995-02-09 17:18:10 +0000224
Martin v. Löwis153c9e42003-04-19 20:59:03 +0000225 The filename parameter is the base filename for the underlying
226 database. As a side-effect, an extension may be added to the
227 filename and more than one file may be created. The optional flag
228 parameter has the same interpretation as the flag parameter of
229 anydbm.open(). The optional protocol parameter specifies the
230 version of the pickle protocol (0, 1, or 2).
231
Tim Peters495ad3c2001-01-15 01:36:40 +0000232 See the module's __doc__ string for an overview of the interface.
233 """
234
Raymond Hettinger1bc82f82004-12-05 03:58:17 +0000235 return DbfilenameShelf(filename, flag, protocol, writeback)