[Python-ideas] Using "||" (doubled pipe) as the null coalescing operator?

Nick Coghlan ncoghlan at gmail.com
Wed Sep 23 17:59:56 CEST 2015


On 24 September 2015 at 00:37, Ryan Gonzalez <rymg19 at gmail.com> wrote:
> *cough* Ruby and Perl *cough*
>
> Ruby has two 'or' operators. One is used normally:
>
> myval = a == 1 || a == 2
> # same as
> myval = (a == 1 || a == 2)
>
> The other one is a bit different:
>
> myval = a == 1 or a == 2
> # same as
> (myval = a == 1) or (a == 2)
>
> It's used for simple nil and false elision, since Ruby has a stricter
> concept of falseness than Python.

The Perl, Ruby and PHP situation is a bit different from the one
proposed here - "or" and "||" are semantically identical in those
languages aside from operator precedence.

That said, it does still count as a point in favour of "??" as the
binary operator spelling - experienced developers are unlikely to
assume they already know what that means, while the "||" spelling
means they're more likely to think "oh, that's just a higher
precedence spelling of 'or'".

The only other potential spelling of the coalescence case that comes
to mind is to make "?" available in conditional expressions as a
reference to the LHS:

    data = data if ? is not None else []
    headers = headers if ? is not None else {}
    title = user_title if ? is not None else local_default_title if ?
is not None else global_default_title
    title?.upper()
    person?['name']

The expansions of the latter two would then be:

    title if ? is None else ?.upper()
    person if ? is None else ?['name']

Augmented assignment would still be a shorthand for the first two examples:

    data ?= []
    headers ?= {}

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list