anyconfig.mergeabledict

Merge-able dict.

anyconfig.mergeabledict.jsnp_unescape(jsn_s)

Parse and decode given encoded JSON Pointer expression, convert ~1 to / and ~0 to ~.

>>> jsnp_unescape("/a~1b")
'/a/b'
>>> jsnp_unescape("~1aaa~1~0bbb")
'/aaa/~bbb'
anyconfig.mergeabledict.parse_path(path, seps=('/', '.'))

Parse path expression and return list of path items.

Parameters:
  • path – Path expression may contain separator chars.
  • seps – Separator char candidates.
Returns:

A list of keys to fetch object[s] later.

>>> parse_path('')
[]
>>> parse_path('/')  # JSON Pointer spec expects this behavior.
['']
>>> parse_path('/a') == parse_path('.a') == ['a']
True
>>> parse_path('a') == parse_path('a.') == ['a']
True
>>> parse_path('/a/b/c') == parse_path('a.b.c') == ['a', 'b', 'c']
True
>>> parse_path('abc')
['abc']
anyconfig.mergeabledict.get(dic, path, seps=('/', '.'))

getter for nested dicts.

Parameters:
  • dic – Dict or dict-like object
  • path – Path expression to point object wanted
  • seps – Separator char candidates
Returns:

A tuple of (result_object, error_message)

>>> d = {'a': {'b': {'c': 0, 'd': [1, 2]}}, '': 3}
>>> get(d, '/')  # key becomes '' (empty string).
(3, '')
>>> get(d, "/a/b/c")
(0, '')
>>> sorted(get(d, "a.b")[0].items())
[('c', 0), ('d', [1, 2])]
>>> (get(d, "a.b.d"), get(d, "/a/b/d/1"))
(([1, 2], ''), (2, ''))
>>> get(d, "a.b.key_not_exist")  
(None, "'...'")
>>> get(d, "/a/b/d/2")
(None, 'list index out of range')
>>> get(d, "/a/b/d/-")  
(None, 'list indices must be integers...')
anyconfig.mergeabledict.mk_nested_dic(path, val, seps=('/', '.'))

Make a nested dict iteratively.

Parameters:
  • path – Path expression to make a nested dict
  • val – Value to set
  • seps – Separator char candidates
>>> mk_nested_dic("a.b.c", 1)
{'a': {'b': {'c': 1}}}
>>> mk_nested_dic("/a/b/c", 1)
{'a': {'b': {'c': 1}}}
anyconfig.mergeabledict.set_(dic, path, val, seps=('/', '.'), strategy=None)

setter for nested dicts.

Parameters:
  • dic – MergeableDict instance or other dict-like objects support recursive merge operations.
  • path – Path expression to point object wanted
  • seps – Separator char candidates.
>>> d = MergeableDict.create(dict(a=1, b=dict(c=2, )))
>>> set_(d, 'a.b.d', 3)
>>> d['a']['b']['d']
3
anyconfig.mergeabledict.is_dict_like(obj)
Parameters:obj – Any object may be an instance of MergeableDict or dict.
>>> is_dict_like("a string")
False
>>> is_dict_like({})
True
>>> is_dict_like(create_from({}))
True
anyconfig.mergeabledict.convert_to(mdict)

Convert a MergeableDict instances to a dict object.

Borrowed basic idea and implementation from bunch.unbunchify. (bunch is distributed under MIT license same as this module.)

Parameters:mdict – A MergeableDict instance
Returns:A dict
anyconfig.mergeabledict.create_from(dic)

Try creating a MergeableDict instance[s] from a dict or any other objects.

Parameters:dic – A dict instance
class anyconfig.mergeabledict.MergeableDict

Bases: dict

Dict based object supports ‘merge’ operation.

strategy = 'merge_dicts'
classmethod create(obj)

Create an instance from any object.

classmethod convert_to(mdict)

Create an object from MergeableDict instances

get_strategy()

Merge strategy

update(other, strategy=None, keep=False)

Update members recursively based on given strategy.

Parameters:
  • other – Other MergeableDict instance to merge
  • strategy – Merge strategy
  • keep – Keep original value if type of original value is not a dict nor list. It will be simply replaced with new value by default.
update_w_replace(other)

Update and replace self w/ other if both has same keys.

Parameters:other – object of which type is same as self’s.
>>> md0 = MergeableDict.create(dict(a=1, b=[1, 3], c="abc"))
>>> md1 = MergeableDict.create(dict(a=2, b=[0, 1], c="xyz"))
>>> md0.update_w_replace(md1)
>>> all(md0[k] == md1[k] for k in ("a", "b", "c"))
True
update_wo_replace(other)

Update self w/ other but never replace self w/ other.

Parameters:other – object of which type is same as self’s.
>>> md0 = md1 = MergeableDict.create(dict(a=1, b=[1, 3], c="abc"))
>>> md2 = MergeableDict.create(dict(a=2, b=[0, 1], c="xyz", d=None))
>>> md0.update_wo_replace(md2)
>>> all(md0[k] != md2[k] for k in ("a", "b", "c"))
True
>>> all(md0[k] == md1[k] for k in ("a", "b", "c"))
True
>>> md0["d"] == md2["d"]
True
update_w_merge(other, merge_lists=False, keep=False)

Merge members recursively. Behavior of merge will be vary depends on types of original and new values.

  • dict vs. dict -> merge recursively
  • list vs. list -> vary depends on merge_lists. see its description.
  • other objects vs. any -> vary depends on keep. see its description.
Parameters:
  • merge_lists

    Merge not only dicts but also lists. For example,

    [1, 2, 3], [3, 4] ==> [1, 2, 3, 4] [1, 2, 2], [2, 4] ==> [1, 2, 2, 4]

  • keep – Keep original value if type of original value is not a dict nor list. It will be simply replaced with new value by default.
>>> md0 = md1 = MergeableDict.create(dict(a=1, b=dict(c=2, d=3),
...                                       e=[1, 2, 2]))
>>> md2 = MergeableDict.create(dict(a=2, b=dict(d=4, f=5),
...                                 e=[2, 3, 4]))
>>> md0.update_w_merge(md2, False)
>>> md0["a"] == md2["a"]
True
>>> md0["b"]["d"] == md2["b"]["d"] and md0["b"]["f"] == md2["b"]["f"]
True
>>> md0["e"] == md2["e"]
True
>>> md3 = MergeableDict.create(dict(aaa=[1, 2, 3], ))
>>> md4 = MergeableDict.create(dict(aaa=[4, 4, 5], ))
>>> md3.update_w_merge(md4, True)
>>> md3["aaa"] == [1, 2, 3, 4, 4, 5]
True

Previous topic

anyconfig.backend.xml

Next topic

anyconfig.schema

This Page