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

Andrew Barnert abarnert at yahoo.com
Wed Sep 23 11:21:44 CEST 2015


On Sep 23, 2015, at 02:00, Nick Coghlan <ncoghlan at gmail.com> wrote:
> 
> This may just be my C programmer brain talking, but reading the
> examples in PEP 505 makes me think of the existing use of "|" as the
> bitwise-or operator in both Python and C, and "||" as the logical-or
> operator in C.

The connection with || as a falsey-coalescing operator in C--and C#, Swift, etc., which have a separate null-coalescing operator that's spelled ??--seems like it could be misleading. Otherwise, I like it, but that's a pretty big otherwise.

> One additional wrinkle is that a single "|" would conflict with the
> bitwise-or notation in the case of None-aware index access, so the
> proposal for both that and attribute access would be to make the
> notation "!|", borrowing the logical negation "!" from "!=".

Maybe you should have given the examples first, because written on its own like this it looks unspeakably ugly, but in context below it's a lot nicer...

>    title!|.upper()
>    person!|['name']

This actually makes me think of the ! from Swift and other languages ("I know this optionally-null object is not null even if the type checker can't prove it, so let me use it that way"), more than negation. Which makes the whole thing make sense, but in a maybe-unpythonically out-of-order way: the bang-or means "either title is not None so I get title.upper(), or it is so I get None".

I'm not sure whether other people will read it that way--or, if they do, whether it will be helpful or harmful mnemonically.

> If this particular syntax were to be chosen, I also came up with the
> following possible mnemonics that may be useful as an explanatory
> tool:
> 
>    "||" is a barrier to prevent None passing through an expression
>    "!|" explicitly allows None to pass without error

That's definitely easy to understand and remember. But since Python doesn't exist in isolation, and null coalescing and null conditional operators exist in other languages and are being added to many new ones, it might be useful to use similar terms to other languages. (See https://msdn.microsoft.com/en-us/library/ms173224.aspx and https://msdn.microsoft.com/en-us/library/dn986595.aspx for how C# describes them.)


More information about the Python-ideas mailing list