On Mon, 18 Oct 2021 at 19:29, Guido van Rossum <gu...@python.org> wrote:

> where the convention is that keys at any level may be omitted altogether and 
> config itself may be NOne, then to safely access the value of 
> config["handler"]["parameters"]["y"] we would have to write
>
> y = None  # Default
> if config is not None:
>   handler = config.get("handler")
>   if handler is not None:
>     parameters = handler.get("parameters")
>     if parameters is not None:
>       y = parameters.get("y")
>
> This kind of pattern (and all the various other ways of writing it, e.g. 
> using the walrus or passing {} as the second argument to dict.get()) can be 
> *very* common if that's the kind of data you're given and that's the kind of 
> app you have to write, and you can't control the format of the data.
>
> Using ?. this can be written as
>
> y = config?.get("handler")?.get("parameters")?.get("y")
>
> More examples are in PEP 505 itself, see 
> https://www.python.org/dev/peps/pep-0505/#examples

For this particular usage, I'd much rather have a functional API, like

y = get_config(config, "handler", "parameters", "y")

I understand that writing many helpers like that nested_get is a
chore, and having language support for the operation avoids that chore
- but I'm with Steve in not wanting to see the ?.get() pattern become
"idiomatic Python" as it encourages people *not* to design APIs like
nested_get that allow the user to not even be aware of all that
behind-the-scenes complexity. Sure, you could argue that the ?.
operator makes it easier to write something like get_config, but it's
not *that* hard:

def get_config(config, *keys):
    value = config
    for key in keys:
        if value is None:
            break
        value = value.get(key)
    return value

And the problem with the ?.get style is that it doesn't hide anything
- what if you want/need to change your config data structure (because
the JSON you're reading changes its layout, say)? Without
encapsulation, you can't. And if it's *that* common, adding a stdlib
function or a new dict method is also an option, which doesn't need a
language feature and demonstrates good (IMO) API design for people to
copy.

Anyway, much like Steve, I don't expect to spend a lot of time
fighting this proposal. But I will be sad if it gets accepted, and
even more so if ?. becomes idiomatic in user code.

Paul
_______________________________________________
Python-Dev mailing list -- python-dev@python.org
To unsubscribe send an email to python-dev-le...@python.org
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at 
https://mail.python.org/archives/list/python-dev@python.org/message/55SOK3J6YRIOEBX47INLLTAVUZRMD57Z/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to