Sub topic 1
The bool type: True and False
Prerequisites
This chapter assumes you know basic Python syntax: variables, functions, and if statements. It also assumes you are familiar with the built-in types int, str, list, and dict. You do not need to know anything about comparison operators, None, or truthiness yet. Later chapters cover those topics in detail.
What bool is
bool is the built-in type that represents a truth value. It has exactly two instances, True and False. Both are written with a capital first letter, and both are keywords in Python 3, so you cannot reassign them.
print(type(True)) # <class 'bool'>
print(type(False)) # <class 'bool'>
try:
exec("True = 0")
except SyntaxError as e:
print("SyntaxError:", e)You will meet booleans most often as the result of a comparison such as 3 > 2, or as the value an if statement tests. Those topics come in later chapters. Here we look at the type itself: how it is built, how to create values of it, and how it relates to int.
True and False are singletons
A singleton is a value of which only one instance exists in the running program. True and False are singletons. Every True in your program is the same object, and so is every False. You cannot create a third bool instance. Calling bool(...) never builds a new object. It returns one of the two existing ones.
a = bool(1)
b = bool("text")
c = 5 > 2
print(a is b is c is True) # True
print(id(a) == id(True)) # TrueThis guarantee is why code like x is True can work at all. Most of the time you should not write it, and the later chapter on is versus == explains why. For now, remember that the type has two objects and no more.
Creating booleans with bool()
The bool() constructor converts any value to True or False. It applies Python's truth value testing rules, which the next chapter covers in full. A few results are worth knowing now.
print(bool(1)) # True
print(bool(0)) # False
print(bool("hello")) # True
print(bool("")) # False
print(bool([])) # False
print(bool([0])) # TrueCalling bool() with no argument returns False.
print(bool()) # FalseYou rarely need to call bool() explicitly. Conditions such as if items: apply the same conversion for you. Explicit bool() is useful when you want to store or return an actual True or False, for example in a function that is documented to return a boolean.
bool is a subclass of int
In Python, bool inherits from int. Every boolean is therefore also an integer. True has the integer value 1, and False has the integer value 0.
print(isinstance(True, int)) # True
print(issubclass(bool, int)) # True
print(bool.__mro__) # (<class 'bool'>, <class 'int'>, <class 'object'>)
print(int(True), int(False)) # 1 0
print(True == 1, False == 0) # True TrueThe inheritance was a historical choice. Early Python had no boolean type, and programmers used 1 and 0. When bool was added in Python 2.3, it was made a subclass of int so that old code kept working.
Arithmetic on booleans
Because a boolean is an integer, all integer operations work on it. The result of arithmetic is a plain int, not a bool.
print(True + True) # 2
print(True * 10) # 10
print(False - 1) # -1
print(type(True + True)) # <class 'int'>
print(sum([True, False, True, True])) # 3The last line shows the most common legitimate use of this feature: counting. A list of boolean results can be summed to count how many are true.
scores = [72, 45, 88, 60, 31]
passed = sum(s >= 60 for s in scores)
print(passed) # 3Each comparison produces a bool, and sum adds them as 0s and 1s.
Booleans as indexes
Because True and False behave as 1 and 0, they work as sequence indexes and dictionary keys that match integers.
labels = ["no", "yes"]
print(labels[True]) # yes
print(labels[False]) # no
d = {1: "one"}
print(d[True]) # oneThe dictionary example shows a gotcha. True == 1 and hash(True) == hash(1), so Python treats them as the same key. If you put both in one dictionary, the second assignment overwrites the value of the first, and the key keeps its original object.
d = {}
d[1] = "int"
d[True] = "bool"
print(d) # {1: 'bool'}
print(len(d)) # 1The same applies to sets: {1, True} has one element, and {0, False} has one element.
print({1, True, 1.0}) # {1}
print({0, False}) # {0}Boolean operators on bools
The bitwise operators &, |, and ^ have a special case for booleans. When both operands are bool, the result is a bool. When either operand is a different integer, the result is an int.
print(True & False) # False
print(True | False) # True
print(True ^ True) # False
print(True & 1) # 1
print(type(True & 1)) # <class 'int'>Note that True & 1 returns 1, not True, because one operand is a plain int. The bitwise ~ operator does not follow the pattern. It works on the integer value, so ~True is -2, not False.
print(~True) # -2
print(~False) # -1
print(not True) # FalseUse not for boolean negation. Using ~ on a boolean is nearly always a bug.
You cannot subclass bool
Python's own bool type refuses to be subclassed. This protects the guarantee that only two boolean objects exist.
try:
class MyBool(bool):
pass
except TypeError as e:
print("TypeError:", e)
# TypeError: type 'bool' is not an acceptable base typeYou can still subclass int if you want your own flag-like type. Such a class is a different type, and isinstance(x, bool) is false for its instances.
Showing and converting booleans
str(True) and repr(True) both return the text 'True'. This is why print(True) shows True. Converting from text does not work the way many people expect. Any non-empty string is truthy, including the string "False".
print(str(True)) # True
print(bool("False")) # True
print(bool("0")) # True
print(bool("")) # FalseWhen you parse user input or configuration text, compare the string against the values you accept rather than calling bool() on it.
def parse_bool(text):
value = text.strip().lower()
if value in ("true", "yes", "1", "on"):
return True
if value in ("false", "no", "0", "off"):
return False
raise ValueError(f"not a boolean: {text!r}")
print(parse_bool("Yes")) # True
print(parse_bool(" off ")) # FalseThe same care applies to JSON. JSON uses lowercase true and false, and Python's json module converts them to True and False.
import json
data = json.loads('{"active": true, "admin": false}')
print(data) # {'active': True, 'admin': False}
print(json.dumps(data)) # {"active": true, "admin": false}Type checks: isinstance and type
Since bool is a subclass of int, isinstance(True, int) is True. This surprises code that tries to separate numbers from flags.
def describe(value):
if isinstance(value, bool):
return "boolean"
if isinstance(value, int):
return "integer"
return "other"
print(describe(True)) # boolean
print(describe(1)) # integerThe order of the checks matters. If you tested int first, True would be reported as an integer. The alternative type(value) is bool is stricter. It matches only bool itself, and since bool cannot be subclassed, it is equivalent to the isinstance check here.
The same issue shows up in validation code. A function that accepts "an integer count" will also accept True unless you reject it.
def set_count(n):
if isinstance(n, bool) or not isinstance(n, int):
raise TypeError("n must be an int, not bool")
return n
print(set_count(3)) # 3
try:
set_count(True)
except TypeError as e:
print("TypeError:", e)How the pieces fit together
The diagram shows the class hierarchy and the two instances.
Summary of key behaviors
| Expression | Result | Type of result |
|---|---|---|
| `True + True` | `2` | `int` |
| `True & False` | `False` | `bool` |
| `True & 1` | `1` | `int` |
| `~True` | `-2` | `int` |
| `not True` | `False` | `bool` |
| `bool("False")` | `True` | `bool` |
| `sum([True, True, False])` | `2` | `int` |
Exercises
Exercise
What does this code print, and why? d = {0: "a"}; d[False] = "b"; print(d, len(d))
Show answer
It prints {0: 'b'} 1. False == 0 and hash(False) == hash(0), so Python treats them as the same dictionary key. The assignment replaces the value, and the original key object 0 is kept.
Exercise
A function is_valid(n) should reject True and False but accept any other int. Write the check, and explain why isinstance(n, int) alone is not enough.
Show answer
Use isinstance(n, int) and not isinstance(n, bool). isinstance(n, int) alone is not enough because bool is a subclass of int, so isinstance(True, int) is True.
Exercise
Given flags = [True, False, True], what do sum(flags), ~flags[0], and flags[0] & 1 return, and what type is each result?
Show answer
sum(flags) is 2 (int). ~flags[0] is -2 (int), because ~ works on the integer value 1. flags[0] & 1 is 1 (int), because one operand is a plain int, so the result is not a bool.