Comparing boolean and int using isinstance

心已入冬 提交于 2019-11-27 05:24:07

For historic reasons, bool is a subclass of int, so True is an instance of int. (Originally, Python had no bool type, and things that returned truth values returned 1 or 0. When they added bool, True and False had to be drop-in replacements for 1 and 0 as much as possible for backward compatibility, hence the subclassing.)

The correct way to "solve" this depends on exactly what you consider the problem to be.

  • If you want True to stop being an int, well, too bad. That's not going to happen.
  • If you want to detect booleans and handle them differently from other ints, you can do that:

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

    if type(whatever) in (float, int):
        # Do stuff.
    
  • If you want to detect all floats and ints, you're already doing that.

Yes, this is right, it's a subclass of int, you can verify it using the interpreter:

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

If you only want to check for int:

if type(some_var) is int:
    return True

else:
    return False

See some behaviors (Not so wierd) of python on bool and int

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

How interchangeable can they be used...!

From boolobject.h (win py 2.7) I can see a typedef of int for bool obj. So it is pretty evident that bool has inherited few facial features of int.

#ifndef Py_BOOLOBJECT_H
#define Py_BOOLOBJECT_H
#ifdef __cplusplus
extern "C" {
#endif


typedef PyIntObject PyBoolObject;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!