Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing boolean and int using isinstance

Can someone give me an explanation why isinstance() returns True in the following case? I expected False, when writing the code.

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

My guess would be that its Python's internal subclassing, as zero and one - whether float or int - both evaluate when used as boolean, 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.

like image 625
jake77 Avatar asked Jun 17 '16 18:06

jake77


People also ask

Which Isinstance () code returns a logical truth value?

Python isinstance() Method It returns True if object (first argument) is an instance of the given type, else returns False. Type (the second argument) can be a class, subclass or a tuple of type objects.

What does Isinstance mean in Python?

Python isinstance() Function The isinstance() function returns True if the specified object is of the specified type, otherwise False . If the type parameter is a tuple, this function will return True if the object is one of the types in the tuple.

How do you check if a value is a boolean in Python?

We can evaluate values and variables using the Python bool() function. This method is used to return or convert a value to a Boolean value i.e., True or False, using the standard truth testing procedure.

How do you convert a Boolean to a string in Python?

Convert bool to string: str() You can convert True and False to strings 'True' and 'False' with str() . Non-empty strings are considered True , so if you convert False to strings with str() and then back to bool type with bool() , it will be True .


1 Answers

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.
like image 126
user2357112 supports Monica Avatar answered Sep 21 '22 15:09

user2357112 supports Monica