This proposal is about adding a builtin function or a package to the standard 
library to access an element in an object hierarchy with default behavior i.e. 
if at any level the attribute/key/index does not exist in the path the function 
returns a default value.
Motivation: mapping an object tree to a tuple or a flat object cannot be 
achieved compactly with proper error handling.
Need: I have found a half dozen of packages implementing this functionality on 
github and there is a high number of loosely related libraries.
Here is a motivating example:
animal = {
    'name': 'Wombat', 
    'avg_properties': {
      'height': {'value': 66, 'unit': 'cm'}, 
      'length':{'value': 108, 'unit': 'cm'},
      'weight': {'value': 27, 'unit': 'kg'}
    }
}
assert getpath(animal, ('avg_properties', 'length', 'value'), default='-') == 
108
assert getpath(animal, ('min_properties', 'length', 'value'), default='-') == 
'-'
assert getpaths(animal, 'avg_properties.length.value', default='-') == 108
assert getpaths(animal, 'avg_properties/width/value', sep='/') == None

I created a package to demonstrate the idea: 
https://github.com/axonmatics/quickpath
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/4JIRRUYVGZ6VLIXG24MLIX2N6345GVPK/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to