4

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.

Boseong Choi
  • 2,566
  • 9
  • 22

3 Answers3

3

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.

Boseong Choi
  • 2,566
  • 9
  • 22
1

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

McLovin
  • 555
  • 8
  • 20
-1

Python treats True as 1 and False as 0. Now what you can do here is:

try:
    var = int(string(False))
except ValueError:
    print("Invalid Integer")