[Python-ideas] Null coalescing operators

Steven D'Aprano steve at pearwood.info
Sun Sep 20 09:31:58 CEST 2015

On Sun, Sep 20, 2015 at 09:10:32AM +0300, Serhiy Storchaka wrote:
> On 19.09.15 07:21, Guido van Rossum wrote:
> >I do, but at least the '?' is part of an operator, not part of the name
> >(as it is in Ruby?).
> What to do with the "in" operator?

Absolutely nothing.

I'm not convinced that we should generalise this beyond the three 
original examples of attribute access, item lookup and function call. I 
think that applying ? to arbitrary operators is a case of "YAGNI". Or 
perhaps, "You Shouldn't Need It".

Mark's original motivating use-case strikes me as both common and 
unexceptional. We might write:

# spam may be None, or some object
result = spam or spam.attr
# better, as it doesn't misbehave when spam is falsey
result = None if spam is None else spam.attr

and it seems reasonable to me to want a short-cut for that use-case. But 
the generalisations to arbitrary operators suggested by Guido strike me 
as too much, too far. As he says, going downhill, and quickly.

Consider these two hypotheticals:

spam ?+ eggs
# None if spam is None or eggs is None else spam + eggs

needle ?in haystack
# None if needle is None or haystack is None else needle in haystack

Briefer (more concise) is not necessarily better. At the point you have 
*two* objects in the one term that both need to be checked for None, 
that is in my opinion a code smell and we shouldn't provide a short-cut 
disguising that.

Technically, x.y x[y] and x(y) aren't operators, but for the sake of 
convenience I'll call them such. Even though these are binary operators, 
the ? only shortcuts according to the x, not the y. So we can call 
these ?. ?[] ?() operators "pseudo-unary" operators rather than binary 

Are there any actual unary operators we might want to apply this 
uptalk/shrug operator to? There are (if I remember correctly) only three 
unary operators: + - and ~. I don't think there are any reasonable 
use-cases for writing (say):

    value = ?-x

that justifies making this short-cut available.

So as far as I am concerned, the following conditions should apply:

- the uptalk/shrug ? "operator" should not apply to actual binary 
  operators where both operands need to be checked for None-ness 
  (e.g. arithmetic operators, comparison operators)

- it should not apply to arithmetic unary operators + - and ~

- it might apply to pseudo-operators where only the lefthand 
  argument is checked for None-ness, that is, x.y x[y] and 
  x(y), written as x?.y x?[y] and x?(y).

If I had to choose between generalising this to all operators, or not 
having it at all, I'd rather not have it at all. A little bit of uptalk 
goes a long way, once we have ? appearing all over the place in all 
sorts of expressions, I think it's too much.


More information about the Python-ideas mailing list