comparison sat/memory/persistent.py @ 2644:e107089d6640

core (memory/persistent): better default value handling in LazyPersistentBinaryDict (don't jump to debugger in debug mode if value is not found)
author Goffi <goffi@goffi.org>
date Sun, 29 Jul 2018 18:44:49 +0200
parents 26edcf3a30eb
children 9702025f6dff
comparison
equal deleted inserted replaced
2643:189e38fb11ff 2644:e107089d6640
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. 18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 19
20 from sat.core.i18n import _ 20 from sat.core.i18n import _
21 from sat.core.log import getLogger 21 from sat.core.log import getLogger
22 log = getLogger(__name__) 22 log = getLogger(__name__)
23 from twisted.python import failure
23 24
24 25
25 class MemoryNotInitializedError(Exception): 26 class MemoryNotInitializedError(Exception):
26 pass 27 pass
27 28
197 raise NotImplementedError 198 raise NotImplementedError
198 199
199 def __iter__(self): 200 def __iter__(self):
200 raise NotImplementedError 201 raise NotImplementedError
201 202
203 def _data2value(self, data, key):
204 try:
205 return data[key]
206 except KeyError as e:
207 # we return a Failure here to avoid the jump
208 # into debugger in debug mode.
209 raise failure.Failure(e)
210
202 def __getitem__(self, key): 211 def __getitem__(self, key):
203 """get the value as a Deferred""" 212 """get the value as a Deferred"""
204 d = self.storage.getPrivates(self.namespace, keys=[key], binary=self.binary, profile=self.profile) 213 d = self.storage.getPrivates(self.namespace, keys=[key], binary=self.binary,
205 d.addCallback(lambda data: data[key]) 214 profile=self.profile)
215 d.addCallback(self._data2value, key)
206 return d 216 return d
207 217
208 def __setitem__(self, key, value): 218 def __setitem__(self, key, value):
209 self.storage.setPrivateValue(self.namespace, key, value, self.binary, self.profile) 219 self.storage.setPrivateValue(self.namespace, key, value, self.binary,
220 self.profile)
210 221
211 def __delitem__(self, key): 222 def __delitem__(self, key):
212 self.storage.delPrivateValue(self.namespace, key, self.binary, self.profile) 223 self.storage.delPrivateValue(self.namespace, key, self.binary, self.profile)
213 224
214 def _valueOrDefault(self, value, default): 225 def _defaultOrException(self, failure_, default):
215 if value is None: 226 failure_.trap(KeyError)
216 return default 227 return default
217 return value
218 228
219 def get(self, key, default=None): 229 def get(self, key, default=None):
220 d = self.__getitem__(key) 230 d = self.__getitem__(key)
221 d.addCallback(self._valueOrDefault) 231 d.addErrback(self._defaultOrException, default=default)
222 return d 232 return d
223 233
224 def setdefault(self, key, default): 234 def setdefault(self, key, default):
225 raise NotImplementedError 235 raise NotImplementedError
226 236