Python: logical operations with None and Booleans

Sep 26, 2020 01:26


Originally published at www.ikriv.com. Please leave any comments there.

Coming back to the blog after long break.

Today, almost by accident I found how logical operators work with None in Python. The result is surprising, because it is not commutative.

(False or None) is None (None or False) is False (True or None) is True (None or True) is True (False and None) is False (None and False) is None (True and None) is None (None and True) is None
There seems to be little logic here (pun intended), but in fact it all makes sense. For “or”, if the first operand is truthy, it is returned, and the second operand is not calculated. If the first operant is falsy, the second operand is returned. For “and”, if the first operand is falsy, it is returned, and if it is truthy, the second operand is returned. The definitions are not symmetrical, which results in non-commutative behavior with None.

UPDATE: Javascript behaves the same way with null>. E.g. (null && false) === null, but (false && null) === false.

hacker's diary

Previous post Next post
Up