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:
- Is there a built-in function which acts like
a or b
? - 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.