[Python-ideas] Fwd: Null coalescing operator

David Mertz mertz at gnosis.cx
Sun Sep 11 21:00:42 EDT 2016


On Sun, Sep 11, 2016 at 12:44 PM, Daniel Moisset <dmoisset at machinalis.com>
wrote:

> Both this discussion, PEP 505, and the one a year ago, tend to mix up 2
> related but separate proposals:
> w
> (A) Add a None-coalescing operator (like C# a ?? b, what you would write
> in Python as "a or b" if it didn't have the falsy gotcha)
> (B) Add some None-aware navigation operators ( The "?.", "?()", "?[]", or
> what you would write in python as "a and a.attribute" if it didn't have the
> falsy gotcha)
>

I readily confess that my initial comments here had a think-o about just
what was being discussed, notwithstanding having also followed the
discussion a year ago.  I somehow had in mind that "None-coalescing" meant
something like "get to None on failure" (i.e. *coalesce* to)

I think the reason I thought wrong was because the second set of syntax
really encourages that wrong way of thinking.  I don't find `a ?? b`
particularly ugly, even if I don't entirely want it.  Similarly if it were
spelled `a || b`.  Both of those feel easy to conceptualize and teach as
"another kind of short-circuiting, similar to boolean operators."  Maybe an
actual word is better? `a ifNone b`? `a failto b`?

Falsey is similar to None-like (I know it's actually None-identical), so
the shortcut idea is familiar.  So I'm only -0 on that idea.

However, the None-aware navigation operators suggest something very
different.  `a?.foo` MIGHT BE an attribute access, or it might not be.
Likewise, `a?[x]` might be an item get or it might not be.  And `a?(y)`
might or might not be a function call.  Obviously, if some or all of those
forms are not added they are simply syntax errors.

What operation happens when we use these syntax forms is "it depends"...
that answer feels less straightforward than "We call
`a.__getattr__('foo')`" (or `a.__getitem__(x)` or `a.__call__(y)`, as the
case may be).  Even if there were some characters I found attractive for
these "it depends" operations, that would introduce a needless
non-uniformity into the semantics of Python.

In contrast, a fully spelled out ternary doesn't give me this uneasiness.
Of course the following expression might be one thing or the other, but
that's more obvious in the ternary syntax (also more general, you can put
*any* values on both branches of the ternary):

    None if a is None else a.foo

-- 
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons.  Intellectual property is
to the 21st century what the slave trade was to the 16th.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160911/277b05bc/attachment-0001.html>


More information about the Python-ideas mailing list