Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isinstance(False, int) returns True [duplicate]

I want to determine if a variable is an integer, so I use the following code:

if isinstance(var, int):
    do_something()

but when var = False, the do_something function is executed.

when var = None, the isinstance() function works normaly.

like image 566
Machine Markus Avatar asked Oct 29 '25 16:10

Machine Markus


2 Answers

Because bool is a subclass of int.
You can find it in builtins.py

class bool(int):
    """
    bool(x) -> bool

    Returns True when the argument x is true, False otherwise.
    The builtins True and False are the only two instances of the class bool.
    The class bool is a subclass of the class int, and cannot be subclassed.
    """

So issubclass(bool, int) also True.
isinstance(x, y) is True when x's type is a derived class of y's type.

like image 89
Boseong Choi Avatar answered Oct 31 '25 07:10

Boseong Choi


In Python3 boolean is defined as a subclass of integer.

That means True is equivalent to 1 where as False is equivalent to 0

You can find the more details here. The exact same explanation from that link is:

There are three distinct numeric types: integers, floating point numbers, and complex numbers. In addition, Booleans are a subtype of integers


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!