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)https://docs.python.org/3/library/stdtypes.html#truth-value-testing
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 typebool
which is a subclass ofint
….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
andFalse
. - zero of any numeric type:
0
,0.0
,0j
,Decimal(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') # ✓