Improving Python's SimpleNamespace
Improving Python's SimpleNamespace
Posted May 2, 2020 7:12 UTC (Sat) by dtlin (subscriber, #36537)In reply to: Improving Python's SimpleNamespace by NYKevin
Parent article: Improving Python's SimpleNamespace
Seems to me that it makes more sense to keep splitting the responsibility of the caller:
def deep_getitem(obj, *path): return functools.reduce(operator.getitem, path, obj) deep_getitem(catalog, *'clothing mens shoes extra_wide quantity'.split())
The caller should know what an appropriate separator is, and could even build the path up from multiple parts split in different ways if that's appropriate.
Although that reminds me of how convenient Perl's qw(...)
and Ruby's %w[...]
are. I wonder if there might be interest in some hypothetical w-string in Python, such that
w'hello world' == ["hello", "world"]
Posted May 2, 2020 8:47 UTC (Sat)
by smurf (subscriber, #17840)
[Link] (1 responses)
One more character and it works today.
w/'hello world'
Writing the three-line singleton object 'w', with an appropriate dunder method, is left as an exercise to the reader.
Posted May 2, 2020 10:30 UTC (Sat)
by dtlin (subscriber, #36537)
[Link]
Yeah, that would be simple, but precedence doesn't work out entirely in our favor:
would result in
Posted May 3, 2020 14:35 UTC (Sun)
by kleptog (subscriber, #1183)
[Link] (1 responses)
I've often ended up coding methods to do this, but it'd be cool if there was something standard.
Posted May 7, 2020 5:45 UTC (Thu)
by njs (subscriber, #40338)
[Link]
Improving Python's SimpleNamespace
Improving Python's SimpleNamespace
w/'hello world'[0]
"h"
instead of "hello"
.
When dealing with complex data structures from a database or client it's useful to have a kind of "deep get" like you have, but one that gracefully handles missing entries well. Otherwise you end up with horrors like:
Improving Python's SimpleNamespace
a.get('foo', {}).get('bar', {}).get('baz', None)
Ideally you'd like something that also handled arrays, but Python doesn't have an easy way to index an array with a default when you go off the end.
Improving Python's SimpleNamespace