pythonpython-3.xnonetypenull-coalescing-operatornull-coalescing

Multi-argument null coalesce and built-in "or" function in Python


Python has a great syntax for null coalescing:

c = a or b

This sets c to a if a is not False, None, empty, or 0, otherwise c is set to b.

(Yes, technically this is not null coalescing, it's more like bool coalescing, but it's close enough for the purpose of this question.)

There is not an obvious way to do this for a collection of objects, so I wrote a function to do this:

from functools import reduce

def or_func(x, y):
    return x or y

def null_coalesce(*a):
    return reduce(or_func, a)

This works, but writing my own or_func seems suboptimal - surely there is a built-in like __or__? I've attempted to use object.__or__ and operator.__or__, but the first gives an AttributeError and the second refers to the bitwise | (or) operator.

As a result I have two questions:

  1. Is there a built-in function which acts like a or b?
  2. Is there a built-in implementation of such a null coalesce function?

The answer to both seems to be no, but that would be somewhat surprising to me.


Solution

  • It's not exactly a single built-in, but what you want to achieve can be easily done with:

    def null_coalesce(*a):
        return next(x for x in a if x)
    

    It's lazy, so it does short-circuit like a or b or c, but unlike reduce.

    You can also make it null-specific with:

    def null_coalesce(*a):
        return next(x for x in a if x is not None)