Re:Box: Python dictionaries with recursive dot notation access
by CloudYeller on Friday May 05, 2017 @06:47PM
(#14277378)
You can get part of the way there with operator.attrgetter:
NT = collections.namedtuple('NT', ['x', 'y'])
nt1 = NT(1, 2)
nt2 = NT(nt1, 'asdf')
assert nt2.x.y == 2
get_two = operator.attrgetter('x.y')
assert get_two(nt2) == 2
If you wrap the operator.attrgetter in a try/catch, you can force a default too: https://pastebin.com/bFxGr22E
Re:Box: Python dictionaries with recursive dot notation access
by smoe on Saturday May 06, 2017 @02:06PM
(#14281512)
I never thought much about best implementation because I only used it i think once in ten years. But afaik I used something like this, that does the job and is easy to read
_empty = object()
def deep_get(dct, dotted_path, default=_empty):
for key in dotted_path.split('.'):
try:
dct = dct[key]
except KeyError:
if default is _empty:
raise
return default
return dct
Re:Box: Python dictionaries with recursive dot notation access
by nerdponx on Friday May 05, 2017 @09:35PM
(#14278171)
You can use `get` from the `toolz` package:
toolz.get(value, ['this', 'that', 'the_other']
There's also a Cython implementation called `cytoolz`.
Personally I'd prefer a helper functions like
You stil have to check the docs/source what exactly happens, but it is just one simple function instead of magic methods. And i can keep using plain dicts everywhere.EDIT: To clarify a bit. An experienced Python developer should immediately recognize a call like `deep_get(value,'this.that.the_other')` as something project/framework specific and not built-in, while `value.this.that.the_other` is ambiguous.