[Python-ideas] Null coalescing operators

Guido van Rossum guido at python.org
Tue Sep 22 00:54:32 CEST 2015

On Mon, Sep 21, 2015 at 3:45 PM, Terry Reedy <tjreedy at udel.edu> wrote:

> 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 didn't write that, you [Terry] did. It looks like our mailers don't
understand each other's quoting conventions. :-( )

> 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".
> try:
>     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 ;-).

Eew. That try/except is not only very distracting and interrupts the flow
of both the writer and the reader, it may also catch errors, e.g. what if
the method being called raises an exception (not a problem with upper(),
but definitely with user-defined methods).

--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150921/fbf281e1/attachment.html>

More information about the Python-ideas mailing list