Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "is" and "isinstance" in python

Tags:

python

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?

like image 853
william007 Avatar asked Oct 04 '14 13:10

william007


People also ask

What is Isinstance () 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.

What is the difference between the type () and Isinstance () in Python?

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.

Is Isinstance better than type?

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.

Why should I use Isinstance?

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 .


1 Answers

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.

like image 96
thefourtheye Avatar answered Oct 02 '22 03:10

thefourtheye