dict.get_deep()

Chris Angelico rosuav at gmail.com
Sun Apr 3 17:52:14 EDT 2022


On Mon, 4 Apr 2022 at 05:19, Marco Sulla <Marco.Sulla.Python at gmail.com> wrote:
>
> On Sun, 3 Apr 2022 at 18:57, Dieter Maurer <dieter at handshake.de> wrote:
> > You know you can easily implement this yourself -- in your own
> > `dict` subclass.
>
> Well, of course, but the question is if such a method is worth to be
> builtin, in a world imbued with JSON. I suppose your answer is no.

I think not, for a slightly different reason: There are many small
variants of it that might be needed. For instance, I have a system of
persistent data that is backed by a JSON file, and I have a path
function that does this:

def path(self, *parts):
    ret = self.data # always a dict
    for part in parts:
        if part not in ret:
            ret[part] = {}
            self.save() # queue a save for the next idle time
        ret = ret[part]
    return ret

It's used something like this:

cfg = persist.path("channels", channame, "alerts", "host")

and if there had previously been no configs, you'll get back an empty
dict, not None, not an error, etc.

This version uses dictionaries only. A version that also supports
lists would require one more check before the "part not in ret" check
(probably something like "if this is a list, and you're asking for an
index higher than the current one, append elements till we get
there"), and a version that doesn't autosave wouldn't need the save()
call, etc, etc, etc.

IMO this is an extremely useful tool to have in your own toolbelt, but
I actually don't use *identical* versions of it very often. They're
usually subtly different from each other, due to the slight
differences in usage.

ChrisA


More information about the Python-list mailing list