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.
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.
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.
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.
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 .
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With