Arovit
Arovit

Reputation: 3719

python not strict type check for bool

I have always read that python has strict type checks -

>>> 1 + 'hello'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

This is fine since we cannot add int to a string

But why is the following allowed ?

>>> True + False
1
>>> True + 0
1

Why is strict checking not supported while adding int to a boolean ?

Upvotes: 3

Views: 1288

Answers (4)

Tim Peters
Tim Peters

Reputation: 70735

>>> issubclass(bool, int)
True

That explains everything. That is, bool is a subclass of int. That's why you can use a bool anywhere an int is allowed.

For a lot of detail, see the PEP that introduced the type.

EDIT: gloss

Note that Python didn't have a bool type for the first decade of its life. Conceptually "true/false" operations usually returned 1 or 0 instead. And Python programmers exploited that as often as, say, K&R C programmers exploited it. For example,

sum(x < 2 for x in some_list)

returned the number of elements in some_list less than 2. When adding the bool type, of course operators like < had to be changed to return True or False instead, but an enormous amount of code relying on 1 or 0 return values would have been broken. That's a key reason for why bool was made a subtype of int, restricted to the values 0 and 1 (with the fancier names False and True).

Upvotes: 8

Dmitry Zagorulkin
Dmitry Zagorulkin

Reputation: 8548

PEP 285:

This PEP proposes the introduction of a new built-in type, bool, with two constants, False and True. The bool type would be a straightforward subtype (in C) of the int type, and the values False and True would behave like 0 and 1 in most respects (for example, False==0 and True==1 would be true) except repr() and str(). All built-in operations that conceptually return a Boolean result will be changed to return False or True instead of 0 or 1; for example, comparisons, the "not" operator, and predicates like isinstance().

it's possible because True is also 1 and False is also 0 (and vice versa):

>>> 1 + False
1
>>>
>>> 1 + 1
2
>>> True + 2
3
>>> False
False
>>> False + 4
4
>>>
>>> type(True+1)
<type 'int'>
>>>

also you have to know that None type is not eqvivalent to 0:

>>> None + True
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'bool'
>>>
>>> None is 0
False

Upvotes: 1

bruno desthuilliers
bruno desthuilliers

Reputation: 77942

Because Python's boolean type is a subclass of integer.

Upvotes: 6

Deelaka
Deelaka

Reputation: 13721

True or False simply evaluates to:

>>> 1 or 0
1

and True + 0 evaluates to the same thing

eg:

>>> int(True)
1
>>> int(False)
0

The or statement returns True if one of the arguments is True

Upvotes: 1

Related Questions