|
|
Subscribe / Log in / New account

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"]


to post comments

Improving Python's SimpleNamespace

Posted May 2, 2020 8:47 UTC (Sat) by smurf (subscriber, #17840) [Link] (1 responses)

> w'hello world' == ["hello", "world"]

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.

Improving Python's SimpleNamespace

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:

w/'hello world'[0]

would result in "h" instead of "hello".

Improving Python's SimpleNamespace

Posted May 3, 2020 14:35 UTC (Sun) by kleptog (subscriber, #1183) [Link] (1 responses)

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:
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.

I've often ended up coding methods to do this, but it'd be cool if there was something standard.

Improving Python's SimpleNamespace

Posted May 7, 2020 5:45 UTC (Thu) by njs (subscriber, #40338) [Link]

This kind of stuff is exactly what the 'glom' package (linked in the article) is all about.


Copyright © 2025, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds