Commits

Tomasz Rybarczyk  committed b40d3e3

Take default value in execute_update

  • Participants
  • Parent commits 7cc2ff8

Comments (0)

Files changed (2)

File redis_dict.py

 import redis
 import time
 
+_missing = object()
+
 class RedisDict(object):
 
     def __init__(self, name, connection, serializer=pickle):
     def items(self):
         return [(k, self._deserialize(v)) for k,v in self._redis.hgetall(self.name).items()]
 
-    def execute_update(self, key, updater, retry=0, interval=100):
+    def execute_update(self, key, updater, retry=0, interval=100, default=_missing):
         with self._redis.pipeline() as pipe:
             while retry+1:
                 try:
                     pipe.watch(self.name)
-                    old_value = self._deserialize(pipe.hget(self.name, key))
                     if not pipe.hexists(self.name, key):
-                        pipe.reset()
-                        raise KeyError('Key doesn\'t exists')
+                        if default is _missing:
+                            pipe.reset()
+                            raise KeyError('Key doesn\'t exists')
+                        else:
+                            old_value = default
+                    else:
+                        old_value = self._deserialize(pipe.hget(self.name, key))
                     new_value = updater(old_value)
                     pipe.multi()
                     pipe.hset(self.name, key, self._serialize(new_value))
                 else:
                     break
 
+
     def get(self, key, default=None):
         return self[key] if key in self else default
 
         self.redis_dict['one'] = 1
         self.assertRaises(KeyError, lambda: self.redis_dict.execute_update('nonexisting', lambda: None))
 
+    def test_default_value_is_used_for_non_existing_key(self):
+        self.redis_dict['one'] = 1
+        self.redis_dict.execute_update('two', lambda v: v, default='default')
+        self.assertEqual(set([('one', 1), ('two', 'default')]), set(self.redis_dict.items()))