1

I am currently working on understanding types and how to check for them. I'm now stuck on this:

input_variable = True

print(type(input_variable))

print(isinstance(input_variable, bool))
print(isinstance(input_variable, int))
print(isinstance(input_variable, str))
print(isinstance(input_variable, float))

This outputs:

<class 'bool'>

True
True
False
False

I'm expecting the variable to be a bool, which is confirmed by the first type() statement. I'm trying to understand why both the isinstance() checks for bool and int return true. So I tried to cast my original variable to an int with

int(input_variable)

which gives me 1. I sort of understand this with True = 1 and False = 0, but I'm still confused as to why I don't have to explicitly cast the variable to an int to have isinstance() recognize it as such.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Ezra
  • 11
  • 1
  • 4
    In Python, bool is a subtype of int. – khelwood Dec 30 '21 at 20:20
  • You're going to get a kick out of this when you get to abstract classes. You can retroactively insert a parent type into a class. – Mad Physicist Dec 30 '21 at 20:22
  • 2
    Worth reading [PEP 285 - Adding a bool type](https://www.python.org/dev/peps/pep-0285/) – buran Dec 30 '21 at 20:25
  • 3
    @buran Good read. I wonder how many reviewers today would rethink their answer to #4, and #6 also seems like a poor decision (choosing a public facing interface because it simplifies the implementation?), though one that backwards compatibility forced at the time. – chepner Dec 30 '21 at 20:29
  • Because `issubclass(book, int)` and `isinstance(x, Klass)` checks if `x` has `Klass` anywhere in its method resolution order – juanpa.arrivillaga Dec 30 '21 at 21:13

0 Answers0