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
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
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 valuesFalseandTrueare 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
Trueif you didisinstance(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
Because booleans are a subtype of integers. See the docs.