If you are puzzled why bool
is a valid index argument: this is simply for consistency with the fact that bool
is a subclass of int
and in Python it is a numerical type.
If you are asking why bool
is a numerical type in the first place then you have to understand that bool
wasn't present in old releases of Python and people used int
s instead.
I will add a bit of historic arguments. First of all the addition of bool
in python is shortly described in Guido van Rossum (aka BDFL) blogpost: The History of Python: The history of bool
, True
and False
. The type was added via PEP 285.
The PEP contains the actual rationales used for this decisions. I'll quote some of the portions of the PEP below.
4) Should we strive to eliminate non-Boolean operations on bools
in the future, through suitable warnings, so that for example
True+1
would eventually (in Python 3000) be illegal?
=> No.
There's a small but vocal minority that would prefer to see
"textbook" bools that don't support arithmetic operations at
all, but most reviewers agree with me that bools should always
allow arithmetic operations.
6) Should bool
inherit from int
?
=> Yes.
In an ideal world, bool
might be better implemented as a
separate integer type that knows how to perform mixed-mode
arithmetic. However, inheriting bool
from int
eases the
implementation enormously(in part since all C code that calls
PyInt_Check()
will continue to work -- this returns true for
subclasses of int
). Also, I believe this is right in terms of
substitutability: code that requires an int
can be fed a bool
and it will behave the same as 0
or 1
. Code that requires a
bool
may not work when it is given an int
; for example, 3 & 4
is 0, but both 3 and 4 are true when considered as truth
values.
Because bool
inherits from int
, True+1
is valid and equals 2
, and
so on. This is important for backwards compatibility: because
comparisons and so on currently return integer values, there's no
way of telling what uses existing applications make of these
values.
Because of backwards compatibility, the bool type lacks many
properties that some would like to see. For example, arithmetic
operations with one or two bool arguments is allowed, treating
False as 0 and True as 1. Also, a bool may be used as a sequence
index.
I don't see this as a problem, and I don't want evolve the
language in this direction either. I don't believe that a
stricter interpretation of "Booleanness" makes the language any
clearer.
Summary:
- Backwards compatibility: there was plenty of code that already used
int
s 0
and 1
to represent False
and True
and some of it used those values in numerical computations.
- It wasn't seen as a big deal to have a "non-textbook"
bool
type
- Plenty of people in the Python community wanted these features
- BDFL said so.