Slightly more complex examples include incrementing a numeric value, setting a value if a condition is met or pushing/popping from lists. These operations also have the benefit that they are atomic.
increment_by
increments a value found under a given key. The value has to be a numeric value in order for this operation to succeed:
store.increment_by(key, amount)
set_value_if
sets a value if a condition is met. If the value stored under the given key matches the same value as the given previous value, then the given value parameter will become the new value of the key.
store.set(key, 1) # set a value
# sets 2 only if the previous value of *key* is 1
store.set_value_if(key, value=2, previous_value=1)
set_child_values/remove_child_values
can be useful for storing/removing nested values. The value under the given key has to be a dictionary.
```python
store.set_child_values(key, {'a': 'b'}) # store under the given key the key `a` with value `b`
store.remove_child_values(key, ['a', 'c']) # remove the keys `a` and 'c' from the mapping found at `key`
list_pop/list_push
can be useful for manipulating lists.
store.list_push(key, some_value)
store.list_pop(key)
Additionally, list_push
and list_pop
accept a location
parameter.
store.list_push(key, value, location='tail') # Push to the tail of the list
store.list_push(key, value, location='tail_set') # Push to the tail of the list only if the value is not already in the list
store.list_push(key, value, location='head') # Push to the head of the list
store.list_push(key, value, location='head_set') # Push to the head of the list only if the value is not already in the list
store.list_pop(key, location='tail') # Pop from the end of the list
store.list_pop(key, location='head') # Pop from the head of the list
list_pop
can also receive a default
parameter, which will be returned when there is nothing to pop from the given list:
store.list_pop(key, default=1, location='tail')