Do not compare boolean variables to False using == in Python

Consider this snippet:

x = []
bool(x) # prints False
if x == False: # I know I should use `if not x`
    print('x == False') # prints nothing

Although the python documentation stated:

By default, an object is considered true unless its class defines either a bool() method that returns False or a len() method that returns zero’, Here are most of the built-in objects considered false:
* empty sequences and collections: ”, (), [], {}, set(), range(0)

There is no mention of why considered false does not equal to False. In later paragraphs of the same document:

Objects of different types, except different numeric types, never compare equal.

So comparing a list reference to False is wrong to begin with. I was thinking if that is the case then why True == 1 works, because bool and int are different objects right? Wrong according to this SO post:

False object is of type bool which is a subclass of int….booleans are explicitly considered as integers in Python 2.6 and 3.

Do not compare the following to False using ==, because even though they evaluate to false, they do not equal to False:

  • constants defined to be false: None and False.
  • zero of any numeric type: 00.00jDecimal(0)Fraction(0, 1)
  • empty sequences and collections: ''()[]{}set()range(0)

Another reason to not use == when comparing boolean is because it is redundant:

isClosed = True
if isClosed == True: # is equivalent of if True == True, it's like keep appending '== True'

The right way of checking boolean is simply:

if isClosed # when isClosed == True
if not isClosed # when isClosed == False

However, if not isClosed is checking isClosed == False and isClosed is None at the same time:

x = None
if not x:
    print('x is None') # This line gets printed

x = False
if not x:
    print('x is False') # This line gets printed

To make sure x is False but not None:

x = None
if x is not None and not x:
    print('x is not None and is False') # never printed

x = False
if x is not None and not x:
    print('x is not None and is False') # ✓



Leave a Reply

Your email address will not be published. Required fields are marked *