[Python-ideas] Null coalescing operators

Guido van Rossum guido at python.org
Sat Sep 19 18:21:04 CEST 2015

"Uptalk" is an interesting speech pattern where every sentence sounds like
a question. Google it, there's some interesting research.

The "null pattern" is terrible. Uptalk should not be considered a unary
operator that returns a magical value. It's a modifier on other operators
(somewhat similar to the way "+=" and friends are formed).

In case someone missed it, uptalk should test for None, not for a falsey

I forgot to think about the scope of the uptalk operator (i.e. what is
skipped when it finds a None). There are some clear cases (the actual
implementation should avoid double evaluation of the tested expression, of

  a.b?.c.d[x, y](p, q) === None if a.b is None else a.b.c.d[x, y](p, q)
  a.b?[x, y].c.d(p, q) === None if a.b is None else a.b[x, y].c.d(p, q)
  a.b?(p, q).c.d[x, y] === None if a.b is None else a.b(p, q).c.d[x, y]

But what about its effect on other operators in the same expression? I
think this is reasonable:

  a?.b + c.d === None if a is None else a.b + c.d

OTOH I don't think it should affect shortcut boolean operators (and, or):

  a?.b or x === (None if a is None else a.b) or x

It also shouldn't escape out of comma-separated lists, argument lists, etc.:

  (a?.b, x) === ((None if a is None else a.b), x)
  f(a?.b) === f((None if a is None else a.b))

Should it escape from plain parentheses? Which of these is better?

  (a?.b) + c === (None if a is None else a.b) + c    # Fails unless c
overloads None+c
  (a?.b) + c === None if a is None else (a.b) + c    # Could be surprising
if ? is deeply nested

Here are some more edge cases / hypergeneralizations:

  {k1?: v1, k2: v2} === {k2: v2} if k1 is None else {k1: v1, k2: v2}   # ?:
skips if key is None
  # But what to do to skip None values?

Could we give ?= a meaning in assignment, e.g. x ?= y could mean:

  if y is not None:
      x = y

More fun: x ?+= y could mean:

  if x is None:
      x = y
  elif y is not None:
      y += y

You see where this is going. Downhill fast. :-)

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

More information about the Python-ideas mailing list