Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is bool a subclass of int?

Tags:

python

boolean

When storing a bool in memcached through python-memcached I noticed that it's returned as an integer. Checking the code of the library showed me that there is a place where isinstance(val, int) is checked to flag the value as an integer.

So I tested it in the python shell and noticed the following:

>>> isinstance(True, int) True >>> issubclass(bool, int) True 

But why exactly is bool a subclass of int?

It kind of makes sense because a boolean basically is an int which can just take two values but it needs much less operations/space than an actual integer (no arithmetics, only a single bit of storage space)....

like image 692
ThiefMaster Avatar asked Nov 17 '11 14:11

ThiefMaster


People also ask

Is bool a subclass of int?

02:26 Now, since the Boolean class is a subclass of the integer class, it inherits all of the mathematical operations that exist in the integer class.

Is bool class is a subclass of Array class?

'Bool class is subclass of array class' is a FALSE statement. Explanation: Bool type will always used for comparing and return a Boolean.

What is the parent type of int and bool?

True and False are instances of bool and therefore instances of the parent class int , but bool itself is not an instance of int . Being a class it's an instance of type and a subclass of int .


2 Answers

From a comment on http://www.peterbe.com/plog/bool-is-int

It is perfectly logical, if you were around when the bool type was added to python (sometime around 2.2 or 2.3).

Prior to introduction of an actual bool type, 0 and 1 were the official representation for truth value, similar to C89. To avoid unnecessarily breaking non-ideal but working code, the new bool type needed to work just like 0 and 1. This goes beyond merely truth value, but all integral operations. No one would recommend using a boolean result in a numeric context, nor would most people recommend testing equality to determine truth value, no one wanted to find out the hard way just how much existing code is that way. Thus the decision to make True and False masquerade as 1 and 0, respectively. This is merely a historical artifact of the linguistic evolution.

Credit goes to dman13 for this nice explanation.

like image 168
Polynomial Avatar answered Oct 25 '22 22:10

Polynomial


See PEP 285 -- Adding a bool type. Relevent passage:

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).

like image 41
Steven Rumbalski Avatar answered Oct 25 '22 21:10

Steven Rumbalski