Commits

Tomasz Rybarczyk  committed 61552d8

Improve docs

  • Participants
  • Parent commits bdd207a

Comments (0)

Files changed (2)

 # USAGE
 
 ## KEYS
-`RedisDict` accepts only `str` instances as keys - it is impossible relly on Python `__hash__` function as its value can differ on different machines (`hash(None)` is derived from `id`).
+`RedisDict` accepts only `str` instances as keys - it is impossible relly on Python `__hash__` function as its value can differ on different machines (for example `hash(None)` is derived from `None` object `id`).
 
 
 ## UPDATING VALUES
 
-Be careful when you are updating it's content, as you have to overwrite explicite mutable objects after modification:
-
-    >>> import redis_dict, redis
-    >>> connection = redis.Redis()
-    >>> m = redis_dict.RedisDict('new-dict', connection)
-    >>> m['a'] = {'key': 'value'}
-    >>> a = m['a']
-    >>> a['key'] = 'new value'
-    >>> print m['a']['key']
-    value
-    >>> m['a'] = a
-    >>> print m['a']['key']
-    new value
-
+### `RedisDict.execute_update`
+
+If you store mutable objects and want to update them you have to be careful:
+
+    * you have to explicite overwrite value in RedisDict instance:
+
+        >>> import redis_dict, redis
+        >>> connection = redis.Redis()
+        >>> rd = redis_dict.RedisDict('new-dict', connection)
+        >>> rd['a'] = {'key': 'value'}
+        >>> a = rd['a']
+        >>> # this call doesn't affects redis state
+        >>> a['key'] = 'new value'
+        >>> print rd['a']['key']
+        value
+        >>> # you have to explicite override
+        >>> rd['a'] = a
+        >>> print rd['a']['key']
+        new value
+
+    * such an update is not an atomic operation - prefered way to do it is to use `execute_update` method which uses redis transactions (`WATCH` and `MULTI`) to ensure atomicity of operation:
+
+        >>> import redis_dict, redis
+        >>> connection = redis.Redis()
+        >>> rd = redis_dict.RedisDict('new-dict', connection)
+        >>> rd['a'] = {'key': 'value'}
+        >>> # updater receives current value and should return new value
+        >>> rd.execute_update('a', lambda curr_value: dict(curr_value, key='new value'))
+        >>> print rd['a']['key']
+        new value
         self.redis_dict.execute_update('one', lambda v: v+100)
         self.assertEqual(self.redis_dict['one'], 101)
 
+    def test_execute_update_method_on_mutable_object(self):
+        self.redis_dict['dict'] = {'a': 1}
+        self.redis_dict.execute_update('dict', lambda cv: dict(cv, a='A'))
+        self.assertEqual(self.redis_dict['dict'], {'a': 'A'})
+
     def test_items_method(self):
         self.redis_dict['one'] = 1
         self.redis_dict['two'] = 2