3 ms·
That's a tough preference with Python, because of the semantics of what [] and . mean and how ingrained those semantics are in the language. Put another way, th
by jsmthrowaway 9y ago
That's a tough preference with Python, because of the semantics of what [] and . mean and how ingrained those semantics are in the language. Put another way, the following should hold:
x.y == x.__getattr__("y")
x["y"] == x.__getitem__("y")
assignment == set{attr,item}
del x.y, del x["y"], etc
len() and slices of items, not attrs
etc, etc. If you start messing with those semantics, it can become very confusing very quickly in Python and you probably want a data type. Remember that Python gets nervous about cleverness.
One way I've approached your problem before is a recursive helper where I borrowed some concepts from jq:
val = fetch(result_dict, "foo.bar.baz.plonk[0]")
Because then you can also isolate the missing key handling and all that stuff into your helper, rather than changing the semantics of an untyped dict. Aside from typing the responses from APIs -- the way better option -- I found this a reasonably Pythonic approach toward dealing with the annoyance.