Python’s built-in bool function comes in pretty handy for checking the truth and falsity of different types of values.
First, let’s take a look at how True and False are represented in the language.
True and False are numeric values
In Python internals, True is stored as a 1 and False is stored as a 0. They can be used in numeric expressions, like so:
1
2
3
4
|
>>> 1 + False
1
>>> 1 + True
2
|
They can even be compared to their internal representation successfully.
1
2
3
4
|
>>> 0 == False
True
>>> 1 == True
True
|
However, this is just a numeric comparison, not a check of truthiness, so the following comparison returns False:
1
2
|
>>> 5 == True
False
|
bool to the rescue
The number 5 would normally be considered to be a truthy value. To get at its inherent truthiness, we can run it through the bool function.
1
2
|
>>> bool(5) == True
True
|
The following are always considered false:
- None
- False
- Any numeric zero: 0, 0.0, 0j
- Empty sequences: “”, (), []
- Empty dictionaries: {}
- Classes with __bool__() or __len__() functions that return False or 0.
Everything else is considered true.