Sub topic 10
bool is a subclass of int
This chapter assumes you can read basic Python and know the built-in types int, str, list, and dict. It also assumes you have met True, False, and truthiness in earlier chapters. Here you will see how bool is built on top of int, what that allows, and where it can mislead you.
The class relationship
In Python, bool is a subclass of int. Every boolean is an integer. True behaves as 1 and False behaves as 0.
You can check this directly:
print(issubclass(bool, int)) # True
print(bool.__mro__) # (<class 'bool'>, <class 'int'>, <class 'object'>)
print(isinstance(True, int)) # True
print(True == 1, False == 0) # True True
print(hash(True), hash(False)) # 1 0
one = 1
print(True is one) # False
print(type(True + True)) # <class 'int'>True == 1 is true because bool inherits integer equality. True is one is false because they are different objects. True is a singleton of type bool, and 1 is an int object. Equal values do not make identical objects.
Only two bool instances exist, True and False. Calling bool(x) returns one of them, never a new object. Because of this, the identity checks x is True and x is False are reliable. They are rarely what you want, though, as the pitfalls section explains.
Arithmetic with booleans
Any operation that works on int works on bool, and the result is usually a plain int:
| Expression | Result | Type |
|---|---|---|
| `True + True` | `2` | `int` |
| `True * 5` | `5` | `int` |
| `-True` | `-1` | `int` |
| `True / 2` | `0.5` | `float` |
| `True << 3` | `8` | `int` |
| `False - 1` | `-1` | `int` |
Comparisons also work, because they come from int. True > False is True, and sorted([True, False, True]) gives [False, True, True].
Counting with sum()
The most useful application is counting how many items satisfy a condition. A generator of comparison results adds up as 0s and 1s:
scores = [72, 45, 88, 61, 39]
passed = sum(s >= 60 for s in scores)
print(passed) # 3
print(passed / len(scores)) # 0.6
flags = [True, False, True, True]
print(sum(flags) / len(flags)) # 0.75
print(flags.count(True)) # 3This is idiomatic Python and avoids building a filtered list just to take its length. The mean of a list of booleans is the fraction of true values.
Bitwise operators keep the bool type
The operators &, |, and ^ are special-cased. When both operands are bool, the result is a bool. When one operand is a plain int, you get an int.
print(True & False, type(True & False)) # False <class 'bool'>
print(True | False, type(True | False)) # True <class 'bool'>
print(True ^ True) # False
print(True | 2, type(True | 2)) # 3 <class 'int'>These operators do not short-circuit. Both sides are always evaluated. They also have higher precedence than comparisons, so a == 1 & b == 2 does not mean what it appears to mean. Use and and or for conditions in normal code.
The one trap here is ~. It is bitwise inversion on the integer value, not logical negation:
print(~True, ~False) # -2 -1
print(not True) # FalseBoth -2 and -1 are truthy, so if ~flag: is always true. Python 3.12 and later emit a DeprecationWarning when you apply ~ to a bool. Use not for logical negation.
Where the int relationship shows up
Dictionary keys and sets
Equal hashes plus equal values means the same key. Since hash(True) == hash(1) and True == 1, they collide:
d = {}
d[1] = "int"
d[True] = "bool"
d[1.0] = "float"
print(d) # {1: 'float'}
print(len(d)) # 1
print({0, False, 0.0}) # {0}The dictionary keeps the first key object (1) and replaces its value on each later assignment. This can silently merge entries if you build a lookup table whose keys mix booleans and numbers, for example {True: "yes", 1: "one"}. Keep the key types in one dictionary consistent.
Indexing
A bool can be used as a sequence index, because indexes only need to be integers:
options = ["no", "yes"]
print(options[3 > 2]) # yes
print(options[False]) # noThis works, but it is compact at the cost of clarity. A conditional expression ("yes" if cond else "no") says the same thing more plainly.
Formatting
Formatting treats a bool as a string by default, and as an integer when you ask for a numeric format:
print(str(True)) # True
print(f"{True}") # True
print(f"{True:d}") # 1
print("%d" % False) # 0
print(repr(True + 0)) # 1Adding 0 is a quick way to see the integer value, but int(flag) states the intent better.
Validating integers: excluding bool
Since isinstance(True, int) is True, a check meant to accept only integers also accepts booleans. A caller who passes True for a port number or a count gets 1 without any error. When that matters, reject bool explicitly:
def parse_port(value):
if isinstance(value, bool) or not isinstance(value, int):
raise TypeError(f"port must be an int, got {type(value).__name__}")
if not 0 < value < 65536:
raise ValueError(f"port out of range: {value}")
return value
for candidate in (8080, True, "80"):
try:
print(parse_port(candidate))
except TypeError as e:
print("TypeError:", e)
# 8080
# TypeError: port must be an int, got bool
# TypeError: port must be an int, got strThe alternative type(value) is int also excludes bool, but it rejects every other int subclass too. That is stricter than usually intended. Checking for bool first keeps the rest of the int family working.
The same issue affects code that dispatches on type. If you test isinstance(x, int) before isinstance(x, bool), the boolean branch never runs. Always test bool first.
You cannot subclass bool
int can be subclassed, but bool cannot. This keeps True and False the only two instances:
try:
class Tri(bool):
pass
except TypeError as e:
print("TypeError:", e)
# TypeError: type 'bool' is not an acceptable base typeIf you need a three-valued logic type, such as true, false, and unknown, use an enum.Enum or a small class of your own. Do not try to extend bool.
Pitfalls
Seeing booleans as integers leads to a few predictable mistakes.
- Comparing a truthy value to
True.bool(2)isTrue, but2 == TrueisFalse, becauseTrueequals only1. Writeif x:to test truthiness, and usex == Trueonly if you really mean "equals the integer 1". - Using
is Trueto test a value that may be a number.1 is Trueis false even though1 == True.is Trueaccepts only the actualTrueobject, so it fails for truthy values that are notbool, such as1,"yes", or NumPy booleans. - Accidental sums.
sum(x > 0 for x in data)is fine, buttotal = a > b + cassigns aboolbecause comparison has lower precedence than+. Check parentheses when a comparison sits inside arithmetic. - Hidden booleans in numeric data. Mixed data such as
[1, True, 2]sums to4without complaint. Data loaded from spreadsheets or JSON can contain booleans where you expected counts. - Membership tests.
True in [1, 2]isTrue, and[0, 1].index(False)is0, since membership andindexuse equality.
Summary of the rules
boolinherits fromint.Trueis equal to1andFalseis equal to0, but they are distinct objects.- Arithmetic gives
intorfloatresults.&,|, and^between two booleans give abool. hash(True) == hash(1), soTrueand1are the same dictionary key or set element.isinstance(x, int)is true for booleans. Excludeboolexplicitly when you need real integers.~on aboolis integer inversion. Usenotinstead.boolcannot be subclassed.
Exercise
Predict the output of the following code, then explain the result of the last line. d = {True: "a", 1: "b", 1.0: "c"} print(d) print(sum([True, True, False, 5])) print(True | 4, type(True | 4)._name_) print(2 == True, bool(2))
Show answer
The output is:
{True: 'c'}
7
5 int
False True
In the dictionary, True, 1, and 1.0 have equal hashes and compare equal, so they are one key. The first inserted key object (True) is kept, and its value is replaced by each later assignment, ending as 'c'. The sum is 1 + 1 + 0 + 5 = 7. True | 4 mixes a bool with an int, so the result is the int 5. On the last line, 2 == True is False because True equals only 1, while bool(2) is True because any non-zero number is truthy. This is why if x == True is not equivalent to if x.
Exercise
Write a function count_valid(values) that returns how many items in values are real integers greater than zero. Booleans must not count, even though True is an int greater than zero. Use sum() over a generator expression. What does count_valid([3, True, 0, -2, 7, False]) return?
Show answer
One solution:
def countvalid(values):
return sum(
isinstance(v, int) and not isinstance(v, bool) and v > 0
for v in values
)
print(countvalid([3, True, 0, -2, 7, False])) # 2
The generator yields booleans, and sum() adds them as 0 and 1. Only 3 and 7 pass: True is excluded by the bool check, and 0, -2, and False fail the greater-than-zero test (or the bool check). The result is 2.