[Python-ideas] Null coalescing operators

Ron Adam ron3200 at gmail.com
Mon Sep 21 17:28:22 CEST 2015


On 09/20/2015 11:57 PM, Chris Angelico wrote:
> On Mon, Sep 21, 2015 at 2:52 PM, Sven R. Kunze<srkunze at mail.de>  wrote:
>> >I limit myself to materializing default arguments as in:
>> >
>> >def a(b=None):
>> >     b = b or {}
>> >     ...
> As long as you never need to pass in a specific empty dictionary,
> that's fine. That's the trouble with using 'or' - it's not checking
> for None, it's checking for falseness.

 From reading these, I think the lowest-level/purest change would be to 
accommodate testing for "not None".  Something I've always thought 
Python should be able to do in a nicer more direct way.

We could add a "not None" specific boolean operators just by appending ! 
to them.

     while! x:    <-->   while x != None:
     if! x:       <-->   if x != None:

     a or! b      <-->   b if a != None else a
     a and! b     <-->   a if a != None else b
     not! x       <-->   x if x != None else None

Those expressions on the right are very common and are needed because of 
None, False, and 0, are all False values.

It would make for much simpler expressions and statements where they are 
used and be more efficient as these are likely to be in loops going over 
*many* objects.  So it may also result in a fairly nice speed 
improvement for many routines.

While the consistency argument says "if!" should be equivalent to "if 
not", I feel the practicality argument leans towards it being specific 
to "if obj != None".

I believe testing for "not None" is a lot more common than testing for 
"None".  Usually the only difference is how the code is arranged.

I like how it simplifies/clarifies the common cases above.  It would be 
especially nice in comprehensions.

Cheers,
    Ron




More information about the Python-ideas mailing list