[Python-ideas] Null coalescing operators

MRAB python at mrabarnett.plus.com
Sat Sep 19 20:45:59 CEST 2015


On 2015-09-19 17:21, Guido van Rossum wrote:
> "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
> value.
>
> 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 course):
>
>    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
>
It shouldn't escape beyond anything having a lower precedence.

> 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
>
Shouldn't that be:

     if x is not None:
         x = y

? It's the value before the '?' that's tested.

> More fun: x ?+= y could mean:
>
>    if x is None:
>        x = y
>    elif y is not None:
>        y += y
>
Or:

     if x is None:
         pass
     else:
         x += y

> You see where this is going. Downhill fast. :-)
>
Could it be used postfix:

     a +? b === None if b is None else a + b

     -?a === None if a is None else -a

or both prefix and postfix:

     a ?+? b === None if a is None or b is None else a + b

?



More information about the Python-ideas mailing list