Add None coalescing operator in Python

Just like in Javascript there is Nullish coalescing operator(??) for checking for null values, it would be a nice addition to python as python also hasNone .

Currently users often check for None with if statement:

if foo is not None:
    return bar

Or using or :

foo or bar

With or the problem is that it not only check for None but also other bool false values like empty string or False or empty list etc

Adding ?? in python for checking would result in much simpler, which would only check for None values:

foo ?? bar
1 Like

Hi Kumar,

There has been a PEP and a huge amount of discussion about this.

Here are only a few of the threads discussing this idea. There are
probably others.

https://mail.python.org/archives/list/python-ideas@python.org/thread/6NHOUO2IJ64E6XP6VA3QA7YYBEMBBUM3/

https://mail.python.org/pipermail/python-ideas/2015-September/036289.html

Hi @steven.daprano,

Thanks for the links and the PEP, there has been a recent addition to the python syntax i.e. pattern matching so it might be a better time to think about adding this feature to python 3.10, as seeing the PEP it is deferred but not rejected so it might be worth to have a look again.

Unfortunately, there is absolutely no way there is enough time to add such a feature to Python 3.10 :slight_smile:

@pablogsal can it be discussed and possibly implemented for python 3.11 also I am only about adding ?? for None not others in the pep

For that a PEP needs to be written/re-written, discussed in python-dev and then submitted to the Steering Council

@steve.dower Do you have any plans for this PEP as you were the author for the pep ?

My plan is to drop it completely, because I now think the additional syntax would not make Python cleaner or a better language.

1 Like

Yes, I agree with @steve.dower . The readability would be less (to quote PEP 20 “Readability counts”), it’s less obvious (particularly to new programmers), it becomes difficult to teach (my perspective). I’m all for the “less is more”; more syntax, more keywords, a bigger language are all negatives in my view. Cf Perl 5 to Perl 6. I do have a “safe” function that I use, particularly when dealing with SQL (null) and json, for dealing with this issue.