Introducing a Safe Navigation Operator in Python

The difference being here that the walrus actually accomplishes that goal, while this would not.

Lets compare

value = x["a"]["b"]

vs

value = x?["a"]?["b"]

In the case where you have the data you expect, these both extract a value

In the case where you do not have the data you expect, one of these tells you what data you are missing with an exception, the other turns it into None suppressing the context for why it is missing, at a cost of 2 extra characters.

In the “safe navigation” case, you need to always handle None after that, or forward that to users.

In the status quo, if you use exceptions, they are free in the expected path since 3.11

expanding that:

try:
    value = x["a"]["b"]
except KeyError:
    value = default
value = x?["a"]?["b"]

and we can’t anymore. Unless the default is None, because we no longer know if the value was missing or if the value was None. Which means this also only works for things that default to None or can’t contain None to begin with. But the people who want this aren’t validating that None isn’t a value or they wouldn’t need this.

The more terse code is worse here, much like recomputing the same value to save a line was. If the walrus was introduced to improve code on that observation, this should be rejected for that same observation.

8 Likes