For the following code, str
is variable of unicode type but
str is unicode # returns false
isinstance(str, unicode) # returns true
Why is
is return false?
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.
type only returns the type of an object (its class). We can use it to check if variable is of a type str . isinstance checks if a given object (first parameter) is: an instance of a class specified as a second parameter.
The isinstance() function is faster than the type function. We can compare both their performance by using the timeit library. As you can see, the isinstance() function is 30 times faster than type() function.
Using isinstance() function, we can test whether an object/variable is an instance of the specified type or class such as int or list. In the case of inheritance, we can checks if the specified class is the parent class of an object. For example, isinstance(x, int) to check if x is an instance of a class int .
is
operator is used to check if both the objects are one and the same, whereas isinstance
is used to check if the second parameter appears anywhere in the inheritance chain of the first parameter.
So, when you do something like this
print(u"s" is unicode)
you are actually checking if u"s"
is the unicode
, but when you do
print(isinstance(u"s", unicode))
you are checking if u"s"
is of type unicode
and the latter is actually True
.
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