Python comparing boolean and int using isinstance

Can someone explain to me why isinstance() returns True in the following case? I expected False when writing code.

 print isinstance(True, (float, int)) True 

My guess would be that its inner python subclass, both zero and one - float float or int - are both evaluated when used as a logical, but don't know the exact reason.

What would be the most pythonic way to solve such a situation? I could use type() , but in most cases this is considered less pythonic.

+12
source share
4 answers

For historical reasons, bool is a subclass of int , so True is an instance of int . (Initially, Python was not of type bool, and the returned true values โ€‹โ€‹returned 1 or 0. When they added bool , True and False had as much as possible to replace with 1 and 0 for backward compatibility, therefore, for a subclass.)

The right way to โ€œsolveโ€ it depends on what you think is the problem.

  • If you want True stop being int , well, too bad. This will not happen.
  • If you want to detect boolean values โ€‹โ€‹and handle them differently from other ints, you can do this:

     if isinstance(whatever, bool): # special handling elif isinstance(whatever, (float, int)): # other handling 
  • If you want to detect objects whose particular class is exactly equal to float or int , rejecting subclasses, you can do this:

     if type(whatever) in (float, int): # Do stuff. 
  • If you want to detect all floats and ints, you already do this.
+22
source

If you want to check only int :

 if type(some_var) is int: return True else: return False 
+1
source

Yes, thatโ€™s correct, it is a subclass of int, you can check it with the interpreter:

 >>> int.__subclasses__() [<type 'bool'>] 
0
source

Check out some of the (not so weird) Python behaviors on Bool and Int

 >>> 1 == True True >>> 0 == False True >>> True*5 == 0 False >>> True*5 == 5 True >>> 

How interchangeable they can be used ...!

From boolobject.h (win py 2.7), I see a typedef for bool obj. So it's pretty obvious that bool inherited several int facial features.

 #ifndef Py_BOOLOBJECT_H #define Py_BOOLOBJECT_H #ifdef __cplusplus extern "C" { #endif typedef PyIntObject PyBoolObject; 
0
source

All Articles