Why is bool a subclass of int?

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

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

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

But why bool subclass of int ?

This makes sense because the boolean is basically an int that can only take two values, but it requires a lot less operations / spaces than the actual integer (without arithmetic, only one bit of storage space) ....

+74
python boolean
Nov 17 '11 at
source share
3 answers

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

This is perfectly logical if you were around when the bool type was added in python (sometimes around 2.2 or 2.3).

Prior to the introduction of the actual type, bool 0 and 1 were an official representation of the value of truth, similar to C89. To avoid unnecessarily violating imperfect, but working code, the new type bool needs to work just like 0 and 1. This goes beyond just the truth value, but all the integral operations. No one would recommend using a boolean lead to a numerical context, and most people do not recommend equality testing to determine the value of truth; no one wants to know how much the existing code is. Thus, the decision to make True and False masquerade as 1 and 0, respectively. It is simply a historical artifact of linguistic evolution.

The loan goes to dman13 for this nice explanation.

+83
Nov 17 2018-11-11T00:
source share

See PEP 285 - Adding a bool Type . Relevant passage:

6) Should bool inherit from int?

=> Yes.

In an ideal world, bool could be better implemented as a separate integer type that knows how to perform mixed mode arithmetic. However, the inheritance of bool from (partly from all C codes calling PyInt_Check () will continue to work - this returns true for subclasses of int).

+24
Nov 17 '11 at 2:47 a.m.
source share

You can also use help to check the Bool value in the console:

help (True)

 help(True) Help on bool object: class bool(int) | bool(x) -> bool | | Returns True when the argument x is true, False otherwise. | The builtins True and False are the only two instances of the class bool. | The class bool is a subclass of the class int, and cannot be subclassed. | | Method resolution order: | bool | int | object | 

help (False)

 help(False) Help on bool object: class bool(int) | bool(x) -> bool | | Returns True when the argument x is true, False otherwise. | The builtins True and False are the only two instances of the class bool. | The class bool is a subclass of the class int, and cannot be subclassed. | | Method resolution order: | bool | int | object 
0
Jan 23 '18 at 2:40
source share



All Articles