Booleans in python are subclass of integer. Constructor of booleans is bool
. bool class inherits from int class.
issubclass(bool,int) // will return True
isinstance(True,bool) , isinstance(False,bool) //they both True
True
and False
are singleton objects. they will retain same memory address throughout the lifetime of your app. When you type True
, python memory manager will check its address and will pull the value '1'. for False
its value is '0'.
Comparisons of any boolean expression to True
or False
can be performed using either is
(identity) or ==
(equality) operator.
int(True) == 1
int(False) == 0
But note that True
and '1' are not the same objects. You can check:
id(True) == id(1) // will return False
you can also easily see that
True > False // returns true cause 1>0
any integer operation can work with the booleans.
True + True + True =3
All objects in python have an associated truth value. Every object has True
value except:
None
False
0 in any numeric type (0,0.0,0+0j etc)
empty sequences (list, tuple, string)
empty mapping types (dictionary, set, etc)
custom classes that implement __bool__
or __len__
method that returns False
or 0
.
every class in python has truth values defined by a special instance method:
__bool__(self) OR
__len__
When you call bool(x)
python will actually execute
x.__bool__()
if instance x
does not have this method, then it will execute
x.__len__()
if this does not exist, by default value is True
.
For Example for int
class we can define bool as below:
def __bool__(self):
return self != 0
for bool(100), 100 !=0
will return True
. So
bool(100) == True
you can easily check that bool(0)
will be False
. with this for instances of int class only 0 will return False.
another example= bool([1,2,3])
[1,2,3]
has no __bool__()
method defined but it has __len__()
and since its length is greater than 0, it will return True
. Now you can see why empty lists return False
.