Earlier quoted context omitted.
Wait, you choose what to put in the dict. I like being able to map from, say, db objects to internal representations. Why wouldn't you want that?!
The concern is facing something that expects a map, and not knowing how to correctly populate it.
Box: Python dictionaries with recursive dot notation access
121–124 of 124 posts
Re: Box: Python dictionaries with recursive dot notation access
#122Earlier quoted context omitted.
I see the value in the latter for code legibility. My gripe with it is, when I'm new to a project that uses a dict implementation like that: how do I know what happens if for example `that` is missing? Does it raise AttributeError, KeyError or just return None? Personally I'd prefer a helper functions like deep_get(dict_, dotted_path[, default]) -> value You stil have to check the docs/source what exactly happens, bu…
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
_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 dctRe: Box: Python dictionaries with recursive dot notation access
#123This looks really nice. I might be reading the DefaultBox docs wrong, but does it support this: box.might_exist.might_exist.might_exist.desired_key where desired_key would return a default value if one of the keys doesn't exist? I find the bulk of my dict code is checking for keys before access, or using .get('', default) recursively. Gets really hairy for deeply nested dicts.
I also found myself doing that pretty often, so I wrote this: def nget(d, *ks, **kwargs): for k in ks: d = d.get(k) if d is None: return kwargs.get('default') return d >>> d = {'a': {'b': {'c': 12 }}} >>> nget(d, 'a', 'd', 'c', default='Not Found!') 'Not Found!' >>> nget(d, 'a', 'b', 'c') 12
A better implementation would be:
def rget(d, *ks, **kwargs):
for k in ks:
if k not in d:
return kwargs.get('default')
d = d[k]
return d