[Python-ideas] Null coalescing operator

Gustavo Carneiro gjcarneiro at gmail.com
Sat Nov 5 14:29:20 EDT 2016


On 3 November 2016 at 23:06, Steven D'Aprano <steve at pearwood.info> wrote:

> On Thu, Nov 03, 2016 at 12:35:07PM -0700, Chris Barker wrote:
> > On Thu, Nov 3, 2016 at 12:00 PM, MRAB <python at mrabarnett.plus.com>
> wrote:
> >
> > > self.an_arg = the_default if an_arg is None else an_arg
> >
> > > No, ?? is a bit like 'or', except that only None is falsey, so it
> would be:
> > >
> > >     self.an_arg = an_arg ?? the_default
> >
> >
> > thanks! and actually, that reads much better to me.
>
> That suggests a possible different colour for this operator: `?or`.
>
> (Apologies if that's already been suggested and rejected earlier.)
>
> The None-aware "safe navigation" operators ?. and ?[] will be used where
> Python already uses punctuation:
>
>     spam.eggs  # ordinary attribute lookup
>     spam?.eggs  # None-aware attribute lookup
>
>     spam[eggs]  # ordinary item lookup
>     spam?[eggs]  # None-aware item lookup
>
>
> which is simple enough to remember: just prefix your usual operator with
> a question mark to make it None-aware. But one of the disadvantages of
> ?? as an operator is that it replaces a keyword with completely
> unrelated punctuation:
>
>     spam or default  # default only if spam is any Falsey value
>     spam ?? default  # default only if spam is None
>
> Compared to:
>
>     spam ?or default
>
> gives us the same rule: prefix the `or` operator with ? to make it None-
> aware.
>

Agree 100%.  Prefixing an operator with ? meaning that it becomes
None-aware is easy to remember.  Just think of `?or` the same as `or`, but
while `or` is truth-aware, `?or` would be None-aware.  Similarly to other
operators like . and [].

How many times have I  wanted to do something like `foo or bar`, but then
again this is not always correct in case foo is an object that can be true
or false, in which case it  has to be expanded to `foo if foo is not None
else bar`.  With the proposal, we could write `foo ?or bar`, which is
intuitively similar to the well known `foo or bar` expression and therefore
easy to pick up.


>
>
> --
> Steve
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>



-- 
Gustavo J. A. M. Carneiro
Gambit Research
"The universe is always one step beyond logic." -- Frank Herbert
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20161105/23f6062e/attachment.html>


More information about the Python-ideas mailing list