The bool() method

Python offers a method named bool(). This method evaluates the value passed to it as a parameter as either True or False

Syntax

bool(add_parameter_here)

Simply put, it converts any object to one of the two boolean values.

Conditions for evaluating values

The bool() method will evaluate all values as True as long as they do not fit the following criteria:

1. False or None values are given

The code below will evaluate to False, as it contains False and None.

Press + to interact
print(bool(False))
print(bool(None))

The code below will evaluate to True.

Press + to interact
print(bool(True))
print(bool("Hello"))

2. A 0 value of any numeric type (int, float, decimal, etc.) 

The code below will evaluate to False, as it contains zero values.

Press + to interact
print(bool(0))
print(bool(0.0))

The code below will evaluate to True.

Press + to interact
print(bool(1))
print(bool(3.14))

3. An empty sequence or collection is given ((), {}, or [])

The code below will evaluate to False due to the empty collections.

Press + to interact
print(bool(()))
print(bool({}))

The code below will evaluate to True as the collections are not empty.

Press + to interact
print(bool([1, 2, 3]))
print(bool((0, 1, 3)))

4. If an empty string '' is given

The code below will evaluate to False.

Press + to interact
print(bool(''))

The code below will evaluate to True.

Press + to interact
print(bool('Non-empty string'))

5. Overriding the bool() method

Objects or classes that override the bool() method can explicitly define whether they want to be evaluated as true or false.

Press + to interact
class MyObject:
def __bool__(self):
return True

Because our custom class has its own bool() implementation, which is made to return True, the code below will return True.

Press + to interact
class MyObject:
def __bool__(self):
return True
custom_instance = MyObject()
print(bool(custom_instance))

We can also change the implementation to return False.

Press + to interact
class MyObject:
def __bool__(self):
return False
custom_instance = MyObject()
print(bool(custom_instance))