[Python-ideas] Null coalescing operator
Steven D'Aprano
steve at pearwood.info
Thu Nov 3 19:06:39 EDT 2016
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.
--
Steve
More information about the Python-ideas
mailing list