Introducing a Safe Navigation Operator in Python

As someone who teaches Python a lot, I dislike the idea of more syntax as a solution to this problem. Something like this a ??= b?[c]?.f() is just impenetrable to a newcomer. I have always loved that Python can be read by beginners and advanced alike, and more punctuation goes against this.

There is some (old) discussion around this at https://www.reddit.com/r/Python/comments/3lkaxc/pep_505_none_coalescing_operators/, which is mostly very against the idea.

I do understand the requirement when traversing non-rectangular data structures. I’ve also had times where it’s simpler in dealing with SQL engines that return NULL (as None). For the simple case, I just use a simple safe function, and for the more complex case, such as JSON, I either use a different parser, (or pandas which works well with this), or I’ve written a SafeNone class and associated safe function (which supports attribute access, slicing, etc). A SafeNone class solves some of the verboseness of the use of andgetattr function above, but retains the clear use of functions, and doesn’t add any new syntax to the language.
I’ve also seen a nice decorator on the Reddit link that could also work.

As @steve.dower well points out, there’s also the bigger question as to why there are None objects that need to be accessed - sometimes I’ve found the best solution is to stop the None’s getting into the list (or whatever structure). And that may encourage better coding practices.(I like what @rhettinger had to say about this.) It’s easier to get the length of a list that doesn’t have None’s, than to find out how many non-None objects a list has. Also a dict’s get method with a default is sometimes forgotten.

I like what wikipedia has to say about the Null object pattern (and by inference the null/None coalescing operator):
“This pattern should be used carefully as it can make errors/bugs appear as normal program execution. Care should be taken not to implement this pattern just to avoid null checks and make code more readable, since the harder-to-read code may just move to another place and be less standard—such as when different logic must execute in case the object provided is indeed the null object.”

5 Likes