What is Python Null Coalesce and How to Use It

In Python, there is no null value. Instead, it has None. The None or empty string, empty list, False – all are considered as falsy values. Checking falsy values sometimes becomes tricky as it gives unexpected results. Python does not have a built-in function or operator to check null coalesce but you can use still check for None or falsy values but you need to be careful.

Python null coalesce

The null coalesce in Python returns the value of its left-hand operand if it isn’t null or None; otherwise, it evaluates the right-hand operand and returns its result.

Python OR operator can work as null coalesce. The OR is a boolean operator, so it works in a boolean context. If the values are not boolean, they are converted to boolean.

The OR operator does not return only True or False. Instead, it returns the first operand if the first operand returns True, and it returns the second operand if the first operand returns to False.

Example

sm = None

op = sm or "PythonSolved"
print(op)

Output

PythonSolved

In this example, we declared that sm = None. 

Now, using OR operator, we are checking two operands.

  1. The left-hand side is sm whose value is None.
  2. The right-hand side is a string “PythonSolved”.

In our example, None works as a null value, and the OR operator evaluates FALSE to a null value. Hence it will check another operand at the right-hand side of the operator which is a string “PythonSolved” which technically returns True. That’s why we get the PythonSolved in the output.

If you check None and “”(empty string) using coalesce, it won’t return anything.

op = None or ""
print(op)

Output

 python3 app.py

Here, OR operator evaluates False to both operands and that’s why it does not return anything.

If your variable holds something that is either a reference to the instance of a class or None, it is safe to use the same semantics as the null-coalescing operator.

With the use of the OR operator, the problem is that it does not only check for None but also checks for bool falsy values like empty string or False or empty list, etc.

That’s it for this tutorial.

Leave a Comment