[Python-ideas] Null coalescing operators

Terry Reedy tjreedy at udel.edu
Tue Sep 22 00:45:04 CEST 2015

On 9/21/2015 5:48 PM, Guido van Rossum wrote:
> On Mon, Sep 21, 2015 at 2:23 PM, Terry Reedy
> <tjreedy at udel.edu
> <mailto:tjreedy at udel.edu>> wrote:

>     I agree with Paul Moore that propagating None is generally a bad
>     idea. It merely avoids the inevitable exception.

To me, this is the key idea in opposition to proposals that make 
propagating None easier.

> I don't think the big issue is bool(x) being too broad. That's what the
> binary ?? operator is trying to fix, but to me the more useful operators
> are x?.y and x?[y], both of which would still require repetition of the
> part on the left when spelled using ??.
> This is important when x is a more complex expression that is either
> expensive or has a side-effect. E.g. d.get(key)?.upper() would currently
> have to be spelled as (some variant of)
 > "None if d.get(key) is None else d.get(key).upper()"
 > and the ?? operator doesn't really help for the
> repetition -- it would still be "d.get(key) ?? d.get(key).upper()".
> In general to avoid this repetition you have to introduce a local
> variable, but that's often awkward and interrupts the programmer's
> "flow".

     x = d.get(key).upper()
except AttributeError:
     x = None

is also a no-repeat equivalent when d.values are all strings.  I agree 
than "x = d.get(key)?.upper()" is a plausible abbreviation.  But I am 
much more likely to want "x = ''" or another exception as the 
alternative.  I guess some other pythonistas like keeping None around 
more than I do ;-).

Terry Jan Reedy

More information about the Python-ideas mailing list