1

x is of type bool. So why does my code have the output True? I am new to Python. What's going on here?

Code:

x = True
print(isinstance(x, int))

Output:

True
timgeb
  • 76,762
  • 20
  • 123
  • 145
aroN
  • 175
  • 2
  • 2
  • 13
  • @Chris_Rands Is this the appropriate dupe? Equality does not imply subclass-relationships. edit: just noticed that the question body extends beyond the title. – timgeb Nov 26 '18 at 14:40

2 Answers2

2

That's because bool is a subclass of int.

Quoting from the Python Data Model:

Booleans (bool)
These represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects. The Boolean type is a subtype of the integer type, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.

Answer to comment:

Would it also return True if you did isinstance(bool, int)?

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

>>> isinstance(bool, int)
False
>>> isinstance(bool, type)
True
>>> issubclass(bool, int)
True
timgeb
  • 76,762
  • 20
  • 123
  • 145
0

Because booleans are a subtype of integers. See the docs.

TaxpayersMoney
  • 669
  • 1
  • 8
  • 26