anyconfig.dicts

Utility functions to operate on mapping objects such as get, set and merge.

anyconfig.dicts.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.dicts.get(dic, path, seps=('/', '.'), idx_reg=<_sre.SRE_Pattern object>)

getter for nested dicts.

Parameters:
  • dic – a 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}
>>> assert get(d, '/') == (3, '')  # key becomes '' (empty string).
>>> assert 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.dicts.set_(dic, path, val, seps=('/', '.'))

setter for nested dicts.

Parameters:
  • dic – a dict[-like] object support recursive merge operations
  • path – Path expression to point object wanted
  • seps – Separator char candidates
>>> d = dict(a=1, b=dict(c=2, ))
>>> set_(d, 'a.b.d', 3)
>>> d['a']['b']['d']
3
anyconfig.dicts.merge(self, other, ac_merge='merge_dicts', **options)

Update (merge) a mapping object self with other mapping object or an iterable yields (key, value) tuples based on merge strategy ac_merge.

Parameters:
  • others – a list of dict[-like] objects or (key, value) tuples
  • another – optional keyword arguments to update self more
  • ac_merge – Merge strategy to choose
anyconfig.dicts.convert_to(obj, ac_ordered=False, ac_dict=None, **options)

Convert a mapping objects to a dict or object of to_type recursively. Borrowed basic idea and implementation from bunch.unbunchify. (bunch is distributed under MIT license same as this.)

Parameters:
  • obj – A mapping objects or other primitive object
  • ac_ordered – Use OrderedDict instead of dict to keep order of items
  • ac_dict – Callable to convert obj to mapping object
  • options – Optional keyword arguments.
Returns:

A dict or OrderedDict or object of cls

>>> OD = anyconfig.compat.OrderedDict
>>> convert_to(OD((('a', 1) ,)), cls=dict)
{'a': 1}
>>> convert_to(OD((('a', OD((('b', OD((('c', 1), ))), ))), )), cls=dict)
{'a': {'b': {'c': 1}}}