[Python-ideas] Null coalescing operator

Steven D'Aprano steve at pearwood.info
Wed Nov 2 20:19:54 EDT 2016


On Wed, Nov 02, 2016 at 08:46:54AM -0700, Guido van Rossum wrote:

> But first we need to agree on what even the right definition
> of ?. is. It's been frighteningly difficult to explain this even on this
> list, even though I have a very clear view in my head, 

This is Python-Ideas and with respect to the many fine people on this 
list, the culture of the list does tend strongly towards over- 
generalisation which can lead to confusion: it may be hard to understand 
a proposal when multiple competing/alternative proposals are flying past 
all at once.

That should not necessarily be taken as an argument against the feature 
itself: once details are locked down, and alternatives dismissed, the 
feature may not be so hard to understand, even for beginners.

Here's my attempt at an explanation.

    spam?.eggs

is simply syntactic sugar for:

    None if spam is None else spam.eggs


It is not a generalised way of catching AttributeError. Nor is it a 
generalised way of detecting arbitrary empty or missing values. It is 
specific to None.

"spam" can be an expression, not just a name, in which case it is only 
evaluated once:

    database.lookup[expensive+calculation]?.attribute

only performs the expensive calculation and lookup once.

It makes sense to allow ?. to bind "all the way to the right" so that:

    spam?.eggs.cheese.tomato.aardvark

is sugar for:

    None if spam is None else spam.eggs.cheese.tomato.aardvark


The ?[] operator extends this to item lookup:

    spam?[eggs]

is sugar for:

    None if spam is None else spam[eggs]

and the ?? "None-coalescing" operator extends this to general 
expressions:

    spam ?? eggs

being sugar for:

    eggs if spam is None else spam


Again, spam is only evaluated once.





-- 
Steve


More information about the Python-ideas mailing list