[Python-ideas] PEP 505 (None coalescing operators) thoughts

Jeff Hardy jdhardy at gmail.com
Tue Sep 29 22:43:58 CEST 2015

On Tue, Sep 29, 2015 at 10:35 AM, Barry Warsaw <barry at python.org> wrote:

> On Sep 28, 2015, at 03:04 PM, Carl Meyer wrote:
> >But even if they are rejected, I think a simple `??` or `or?` (or
> >however it's spelled) operator to reduce the repetition of "x if x is
> >not None else y" is worth consideration on its own merits. This operator
> >is entirely unambiguous, and I think would be useful and frequently
> >used, whether or not ?. and ?[ are added along with it.
> But why is it an improvement?  The ternary operator is entirely obvious and
> readable, and at least in my experience, is rare enough that the repetition
> doesn't hurt my fingers that much.  It seems like such a radical, ugly new
> syntax unjustified by the frequency of use and readability improvement.

I use it all over the place in C# code, where it makes null checks much
cleaner, and the punctuation choice makes sense:

    var x = foo != null ? foo : "";
    var y = foo ?? "";

 (it also has other uses in C# relating to nullable types that aren't
relevant in Python.)

I'd argue the same is true in Python, if a decent way to spell it can be

    x = foo if foo is not None else ""
    y = foo or? ""

It's pure syntactic sugar, but it *is* pretty sweet.

(It would also make get-with-default unnecessary, but since it already
exists that's not a useful argument.)

- Jeff
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150929/3369f879/attachment-0001.html>

More information about the Python-ideas mailing list